﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using Ledict.ConditionExtract.Base;
using Ledict.ConditionExtract.BLL;
using Ledict.ConditionExtract.BLL.WorkProcess;
using Ledict.ConditionExtract.Common;
using Ledict.ConditionExtract.Frm.NodeTree;
using Ledict.ConditionExtract.Model;
using Ledict.Regex.BLL;
using Ledict.Utility.Extension;
using Ledict.Utility.Frm;
using Ledict.Utility.Frm.Model;
using Ledict.Utility.Frm.Process;
using Ledict.Utility.Helper;
using Ledict.Utility.Msg;
using System.Text;
using System.Xml;
using System.Reflection;
using System.IO;
using Ledict.Regex.Model;
using System.Runtime.CompilerServices;
using Ledict.ConditionExtract.DAL;
using NPOI.POIFS.NIO;
using System.Threading.Tasks;

namespace Ledict.ConditionExtract
{
    /// <summary>
    /// 节点树操作界面
    /// </summary>
    /// <remarks>
    /// 自己理解或使用过的都加入了region，剩下一些是徐仁娜当时写的或我不理解的，后来者了解即可 todo by zhangpeng 2017-01-24
    /// </remarks>
    public partial class NodeTree : BaseForm
    {
        #region 构造单例
        // 静态锁
        private static readonly object Lock = new object();
        /// <summary>
        /// 单例
        /// </summary>
        private static NodeTree _instance;
        /// <summary>
        /// 返回单例
        /// </summary>
        public static NodeTree Instance
        {
            get
            {
                //if (_instance == null || _instance.IsDisposed)
                //{
                //    lock (Lock)
                //    {
                //        if (_instance == null || _instance.IsDisposed)
                //        {
                //            _instance = new NodeTree();
                //        }
                //    }
                //}

                return _instance ?? (_instance = new NodeTree());


            }

        }


        public NodeTree()
        {
            InitializeComponent();
            //GV_ArgumentType 要素属性XML 字典列表            
            dgvAddWfClRel.AutoGenerateColumns = false;
            dgvWfClRelData.AutoGenerateColumns = false;
            GV_ArgumentType.AutoGenerateColumns = false;
            GV_ArgumentType.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgvZX.AutoGenerateColumns = false;
            dgvZX.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgvXSWF.AutoGenerateColumns = false;
            dgvXSWF.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgvGLFW.AutoGenerateColumns = false;
            dgvGLFW.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgvFDXR.AutoGenerateColumns = false;
            dgvFDXR.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            ShowIcon = false;
            tabControl1.TabPages.Remove(Tab_ChooseXML);
            tabControl1.TabPages.Remove(tab_AttrRelXML);
            tabControl1.TabPages.Remove(tabYaoSuZhengJuConfig);
            tabControl1.TabPages.Remove(tabFocusRelation);
            tabControl1.TabPages.Remove(tabPageMDJF);
            tabControl1.TabPages.Remove(tabXSXW);
            CheckForIllegalCrossThreadCalls = false;
            //12行政执法版本才有此功能
            if (ConfigHelper.AppSettings("Version") == "12")
            {
                批量分词ToolStripMenuItem.Visible = 匹配相似违法行为ToolStripMenuItem.Visible = true;
                TypeName = "行政执法";
            }
            else
            {
                批量分词ToolStripMenuItem.Visible = 匹配相似违法行为ToolStripMenuItem.Visible = false;
            }
        }
        #endregion

        #region 共有变量
        readonly TreeDataBLL trbll = new TreeDataBLL();
        readonly AboutRegexBLL regexbll = new AboutRegexBLL();
        readonly NewIDBLL newid = new NewIDBLL();
        readonly CaseCauseBLL casecausebLL = new CaseCauseBLL();
        readonly Express_SourceBLL SourceBLL = new Express_SourceBLL();
        readonly Reg_InfoRegexRelationBLL unitrelation = new Reg_InfoRegexRelationBLL();
        readonly Reg_RegexsBLL addreg = new Reg_RegexsBLL();
        readonly CaseCauseInferConditionBLL infer = new CaseCauseInferConditionBLL();
        readonly RegexParse.RegexParse getregex = new RegexParse.RegexParse();
        readonly AnalysisInferRuleBLL analysisInferRule = new AnalysisInferRuleBLL();
        readonly AnalysisXMLBLL analysisXML = new AnalysisXMLBLL();
        ArgumentTypeXmlBLL argumenttypexmlbll = new ArgumentTypeXmlBLL();
        readonly NodeTree_ArgumentTypeBLL nodetree_argumenttypebll = new NodeTree_ArgumentTypeBLL();
        readonly XmlLabel_SuitTypeRelBLL xmlLabelSuitTypeRelBll = new XmlLabel_SuitTypeRelBLL();
        StringBuilder sb1 = new StringBuilder();
        SYS_CaseCause caseCausexml = new SYS_CaseCause();
        NewIDBLL newidbll = new NewIDBLL();
        Express_MatchSituationBLL eml = new Express_MatchSituationBLL();
        SYS_CaseType_DocTypeBLL sysCTDT = new SYS_CaseType_DocTypeBLL();
        SYS_CaseCauseElement_EvidRelBLL sce = new SYS_CaseCauseElement_EvidRelBLL();
        RegInfoBLL regInfoBll = new RegInfoBLL();
        public static TreeNode clicknode;//点击节点树后，保存该节点
        private SYS_CaseCause objCaseCause;//点击节点树后，保存该节点Model
        private List<TreeNode> NodeList = new List<TreeNode>();//节点树上显示出来的所有节点集合
        private readonly List<TreeNode> SourceNodeList = new List<TreeNode>(); //来源树中显示出来的所有节点集合
        public static string TypeName = "刑事罪名";//默认刑事树
        public string FirId = "1000";//默认刑事树ID
        public string LocateNode = "";//定位节点
        public bool showRegex = false;
        SYS_ArgumentType argumenttypeModel;//字典值
        int RowIndex = -1;
        string node = string.Empty;

        DataTable Typedt = new DataTable();
        private Thread workThread;

        //诉讼请求明细序号
        private string sxqqmxxh = @"  <element xmlPath=""???""> <isSerialField>1</isSerialField> </element> ";
        //其他字典值配置
        private string qtzdzpz = @"  <element xmlPath=""???"">
                                      <checkType>check</checkType>
                                      <sourceType>paramter</sourceType>
                                      <sourceContent>xxx</sourceContent>
                                      <defaultValue/>
                                      <isSerialField/>
                                      <fieldType>int</fieldType>
                                     </element> ";
        //诉讼地位父节点
        private string fryjd = @" <node xmlPath=""???"">
                                  <isPersonNode>1</isPersonNode>
                                  <suitDegreeID>89,90</suitDegreeID>
                                 </node>";
        //诉讼地位同级节点
        private string tjryjd = @" <element xmlPath=""???"">
                                  <checkType>radio</checkType>
                                  <sourceType/>
                                  <sourceContent/>
                                  <defaultValue/>
                                  <isSerialField/>
                                  <fieldType/>
                                  <formatType>spokeNameToPersonName</formatType>
                                  <suitDegreeID>89,90</suitDegreeID>
                                 </element> ";
        //诉讼地位节点
        private string ryjd = @"  <element xmlPath=""???"">
                                  <checkType>radio</checkType>
                                  <sourceType>paramter</sourceType>
                                  <sourceContent>xxx</sourceContent>
                                  <defaultValue/>
                                  <isSerialField/>
                                  <fieldType>int</fieldType>
                                  <formatType>spokeNameTosuitDegreeId</formatType>
                                 </element> ";
        //金额格式转换
        private string jerqzh = @"  <element xmlPath=""???"">
                                      <fieldType>Standardamount</fieldType>
                                     </element> ";
        //日期格式转换
        private string rqgszh = @"  <element xmlPath=""???"">
                                      <fieldType>ChineseDate</fieldType>
                                     </element> ";
        //存放可以操作民事案由的用户
        public static List<string> users = new List<string>();
        //存放可以操作行政执法的用户
        public static List<string> userXZs = new List<string>();
        public int ISCommonCase = 1;//不标记同案

        //被拖拽的节点
        private TreeNode dragNode = null;
        //被拖拽节点的前景色
        private Color dragNodeColor;
        //目标节点的前景色
        private Color dropNodeColor;
        //image集合
        ImageList imageListDrag = new ImageList();
        //计时器
        private System.Windows.Forms.Timer m_timer = new System.Windows.Forms.Timer();

        //拖动过程中路过的节点
        private TreeNode tempDropNode = null;
        //是否是同一个父节点
        private bool m_isValid;
        ArrayList ar = new ArrayList();
        //是否有诉讼地位
        bool hasXSDI = false;
        //是否有货币单位
        bool hasHBDW = false;
        //是否有诉讼请求明细序号
        bool hassxmxxh = false;
        //是否有不为空的属性
        bool hasattribute = false;
        //诉讼地位字典值
        public static string xsdwKeyWord = string.Empty;
        //货币单位字典值
        public static string hbdwKeyWord = string.Empty;

        Dictionary<int, ArrayList> nodeType = new Dictionary<int, ArrayList>();
        public DataTable sysExpressSourceTable = new DataTable();
        Dictionary<string, List<string>> dic = new Dictionary<string, List<string>>();
        Dictionary<string, List<string>> dic1 = new Dictionary<string, List<string>>();
        List<string> table1 = new List<string>();

        SYS_Argument_ElementRelBLL sysArgumentElementBll = new SYS_Argument_ElementRelBLL();
        XF_Punishiment_AdjustmentBLL xfPunishimentAdjustmentBll = new XF_Punishiment_AdjustmentBLL();
        XF_Punishment_GradeBLL xfPunishmentGradeBLL = new XF_Punishment_GradeBLL();
        XF_Grade_RelationBLL xfGradeRelationBLL = new XF_Grade_RelationBLL();
        XF_Major_AddpenaltyBLL xmaBLL = new XF_Major_AddpenaltyBLL();
        Punishment punishMent = new Punishment();
        XF_Punishiment_RelatStatusBLL xprs = new XF_Punishiment_RelatStatusBLL();
        XF_PunishimentGrade_RelatStatusBLL xpgrs = new XF_PunishimentGrade_RelatStatusBLL();
        XF_RelatStatus_GroupBLL xrsg = new XF_RelatStatus_GroupBLL();
        static DataTable dtFDXNode = new DataTable();
        DataTable dtMdjf = new DataTable();
        SYS_DisputeStructureBLL sysDisputebll = new SYS_DisputeStructureBLL();
        private int num = 0;
        //相似违法行为表
        DataTable dtXSWFXW = new DataTable();
        Dictionary<string, string> dicLaws = new Dictionary<string, string>();
        //地域表
        List<SYS_District> dtsysDistrict = new List<SYS_District>();
        //地域与违法行为关系Model
        List<Xzzf_DisWfRelCXModel> xzzfDisWfRelCxModels = new List<Xzzf_DisWfRelCXModel>();
        //显示到添加界面的数据
        List<Xzzf_DisWfRelCXModel> showDisWfRelCxModels = new List<Xzzf_DisWfRelCXModel>();
        #endregion

        #region 界面加载
        /// <summary>
        /// 初始化节点树、案由树、法院树等等
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NodeTree_Load(object sender, EventArgs e)
        {
            cmbCXFS.SelectedIndex = 0;
            clicknode = null;
            GetReason();
            GetMdjfData();
            //CaseCauseTree();//节点树
            //if (LocateNode != "")//定位到某节点
            //{
            //    ToLocateNode(LocateNode);
            //    AddElement.Visible = true;
            //    tVCaseCause.CheckBoxes = true;
            //    Text = @"要素添加";
            //}
            //else
            //{
            panelBase.Visible = false;
            panelType.Location = new System.Drawing.Point(0, 187);
            //AddElement.Visible = false;
            tVCaseCause.CheckBoxes = false;
            //}
            //GetData("t_Case_HeadWords");//案由树
            //GetData("t_Case_JudicialProcedure");//裁决程序
            //GetData("t_Case_Property");//性质
            //GetData("t_Case_ParagraphType");//逻辑段
            //GetData("t_Global_Court");//法院

            m_timer.Interval = 200;
            m_timer.Tick += new EventHandler(timer_Tick);
            sysExpressSourceTable.Columns.Add("ES_ID", typeof(string));
            sysExpressSourceTable.Columns.Add("CC_ID", typeof(string));
            sysExpressSourceTable.Columns.Add("Source_ID", typeof(string));
            sysExpressSourceTable.Columns.Add("Source_ParagraphID", typeof(string));
            sysExpressSourceTable.Columns.Add("Source_Name", typeof(string));
            sysExpressSourceTable.Columns.Add("Source_ParagraphName", typeof(string));
            sysExpressSourceTable.Columns.Add("CC_RegexInfoCode", typeof(string));
            sysExpressSourceTable.Columns.Add("ES_Purpose", typeof(string));
            sysExpressSourceTable.Columns.Add("Source_TextType", typeof(string));
            sysExpressSourceTable.Columns.Add("EI_Name", typeof(string));
            sysExpressSourceTable.Columns.Add("ES_PurposeName", typeof(string));
            sysExpressSourceTable.Columns.Add("Source_TextTypeName", typeof(string));
            userYanZhen();
            switch (TypeName)
            {
                case "刑事罪名":
                    button8_Click(null, null);
                    break;
                case "民事案由":
                    button6_Click(null, null);
                    break;
                case "行政案由":
                    button5_Click(null, null);
                    break;
                case "赔偿案由":
                    button4_Click(null, null);
                    break;
                case "执行案由":
                    button7_Click(null, null);
                    break;
                case "行政执法":
                    btnXZZF_Click(null, null);
                    break;
            }
            if (clicknode != null && clicknode.Text != "刑事罪名")
            {
                var NotePidArr = casecausebLL.GetCaseCauseByCCID(clicknode.Tag.ToString()).AllParentId.Split(',');
                for (var i = 0; i < NotePidArr.Length; i++)
                {
                    if (i != NotePidArr.Length - 1)
                    {
                        var Node = FindNode(NotePidArr[i].ToString());
                        if (Node != null)
                        {
                            Node.Expand();//拖出所有父级节点
                        }
                    }
                    else  //最后一级节点为查找节点
                    {
                        // tVCaseCause.ExpandAll();
                        var node = FindNode(NotePidArr[i].ToString());
                        node.Expand();
                        tVCaseCause.SelectedNode = node;//定位          
                    }
                }
            }
            if (!string.IsNullOrEmpty(LocateNode))//定位到某节点
            {
                QueryNodeTxt.Text = LocateNode;
                QueryNode(QueryNodeTxt.Text.Trim());
            }
            if (showRegex)
            {
                tabControl1.SelectedTab = Tab_Extract;
                // GV_Source.Rows[0].Cells[0].Value = true;
                DataTable dt = GV_Source.DataSource as DataTable;
                for (int i = 0; i < GV_Source.Rows.Count; i++)
                {
                    if (GV_Source.Rows[i].Cells["ES_Purpose_Name"].Value.ToString() == "数据处理文本匹配")
                    {
                        GV_Source.ClearSelection();
                        //GV_Source.Rows[i].Cells["CheckRow"].Value = true;
                        GV_Source.Rows[i].Selected = true;
                        if (GV_Source.Rows[i].Cells["EI_ID"].Value != null)
                        {
                            var EI_ID = GV_Source.Rows[i].Cells["EI_ID"].Value.ToString();
                            if (EI_ID != "")
                            {
                                Random rd = new Random();
                                webBrowser1.Url = new Uri(ConfigHelper.AppSettings("RegexSystemUrl") + "/RegexEdit.aspx?EIID=" + EI_ID + "&a=" + rd.Next(10000, 20000));
                            }
                            else
                            {
                                webBrowser1.Url = null;
                            }
                        }
                        break;
                    }
                }
                //GV_Source.DataSource = dt;
            }
            checkcbSituation1.TreeView.AfterExpand += TreeView_AfterExpand;
            checkcbSituation1.DropDownStyle = ComboBoxStyle.DropDown;
            checkcbSituation2.TreeView.AfterExpand += TreeView_AfterExpand;
            checkcbSituation2.DropDownStyle = ComboBoxStyle.DropDown;
            checkcbSituation3.TreeView.AfterExpand += TreeView_AfterExpand;
            checkcbSituation3.DropDownStyle = ComboBoxStyle.DropDown;
            checkcbSituation4.TreeView.AfterExpand += TreeView_AfterExpand;
            checkcbSituation4.DropDownStyle = ComboBoxStyle.DropDown;
            Typedt = casecausebLL.GetCaseCauseType();
            dtXSWFXW.Columns.AddRange(new DataColumn[] { new DataColumn("check"), new DataColumn("xh"), new DataColumn("CC_Name"), new DataColumn("KeyWords"), new DataColumn("CCSRightState"), new DataColumn("CCSWrongState"), new DataColumn("CCS_ID") });
            //加载右侧地域树选择数据
            SetSysDistrict();
            btnXS.Select();
            btnXS.BackColor = Color.LightSkyBlue;
        }

        /// <summary>
        /// 加载地域树
        /// </summary>
        private void SetSysDistrict()
        {
            cmbCxDistrict.DropDownStyle = cmbSysDistrict.DropDownStyle = ComboBoxStyle.DropDown;
            cmbSysDistrict.checkNodeList.Clear();
            cmbCxDistrict.checkNodeList.Clear();
            SYS_DistrictBLL sysDistrictbll = new SYS_DistrictBLL();
            dtsysDistrict = sysDistrictbll.GetDistrict();
            LoadDistrictFirst(cmbSysDistrict);
            //加载左侧上方地域筛选条件
            LoadDistrictFirst(cmbCxDistrict, 1);
        }

        /// <summary>
        /// 加载第一级地域树
        /// </summary>
        /// <param name="cmbTreeView">下拉框选择树控件</param>
        /// <param name="type">类型0代表默认地域表第一级地域 1加全国条件</param>
        private void LoadDistrictFirst(ComboBoxCheckBoxTreeViewNormal cmbTreeView, int type = 0)
        {
            cmbTreeView.TreeView.Nodes.Clear();
            if (dtsysDistrict != null && dtsysDistrict.Count > 0)
            {
                dtsysDistrict.ForEach(x =>
                {
                    TreeNode node = new TreeNode() { Text = x.DT_Name, Tag = x.DT_ID };
                    cmbTreeView.TreeView.Nodes.Add(node);
                });
                if (type == 1)
                {
                    cmbTreeView.TreeView.Nodes.Insert(0, new TreeNode() { Text = "全国", Tag = "all" });
                }
            }
        }


        /// <summary>
        /// 获取矛盾纠纷结构表信息
        /// </summary>
        private void GetMdjfData()
        {
            dtMdjf = sysDisputebll.GetDisputeStructureData();
        }

        /// <summary>
        /// 法定刑关系加载子集节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TreeView_AfterExpand(object sender, TreeViewEventArgs e)
        {
            e.Node.Nodes.Clear();
            if (dtFDXNode != null && dtFDXNode.Rows.Count > 0 && dtFDXNode.Select(" CC_ParentID='" + e.Node.Tag.ToString() + "' ").Length > 0)
            {
                DataRow[] drs = dtFDXNode.Select(" CC_ParentID='" + e.Node.Tag.ToString() + "' ", " CC_SerialNumb ");
                foreach (var item in drs)
                {
                    TreeNode node = new TreeNode();
                    node.Text = item["CC_Name"].ToString();
                    node.Tag = item["CC_ID"].ToString();
                    if (dtFDXNode.Select(" CC_ParentID='" + node.Tag + "' ").Length > 0)
                    {
                        node.Nodes.Add(new TreeNode());
                    }
                    e.Node.Nodes.Add(node);
                }
            }
        }
        #endregion

        #region 各种树菜单(案由、类型)
        public void GetData(string Tname)
        {
            var dt = trbll.GetTreeHeadWords("", Tname);// 第一层
            var arrayDr = dt.Select();
            foreach (var caseTreeNodeRode in arrayDr)
            {
                var node = new TreeNode();
                node.Text = caseTreeNodeRode["name"] + "(" + caseTreeNodeRode["id"] + ")";
                node.Tag = caseTreeNodeRode["id"];
                switch (Tname)
                {
                    case "t_Case_HeadWords":
                        if (trbll.GetTreeHeadWords(node.Tag.ToString(), Tname).Rows.Count > 0)//第二层
                        {
                            node.Nodes.Add(new TreeNode());
                        }
                        t_Case_HeadWords.TreeView.Nodes.Add(node);
                        break;
                    case "t_Case_JudicialProcedure":
                        t_Case_JudicialProcedure.TreeView.Nodes.Add(node);
                        break;
                    case "t_Case_ParagraphType":
                        t_Case_ParagraphType.TreeView.Nodes.Add(node);
                        break;
                    case "t_Global_Court":
                        if (trbll.GetTreeHeadWords(node.Tag.ToString(), Tname).Rows.Count > 0)//第二层
                        {
                            node.Nodes.Add(new TreeNode());
                        }
                        t_Global_Court.TreeView.Nodes.Add(node);
                        break;
                    default:
                        t_Case_Property.TreeView.Nodes.Add(node);
                        break;
                }
            }
        }
        public void GetTreeHeadWordsChild(TreeNode parentNode, string Tname)
        {
            var dt = trbll.GetTreeHeadWords(parentNode.Tag.ToString(), Tname);// 第一层
            var arrayDR = dt.Select();

            foreach (var caseTreeNodeRode in arrayDR)
            {
                var node = new TreeNode
                {
                    Text = LdFormat.ObjectToString(caseTreeNodeRode["name"]) + @"(" + caseTreeNodeRode["id"] + ")",
                    Tag = caseTreeNodeRode["id"]
                };

                if (trbll.GetTreeHeadWords(node.Tag.ToString(), Tname).Rows.Count > 0)//第二层
                {
                    node.Nodes.Add(new TreeNode());
                }
                parentNode.Nodes.Add(node);
            }
        }

        public void t_Case_HeadWords_AfterExpand(object sender, TreeViewEventArgs e)
        {
            e.Node.Nodes.Clear();
            GetTreeHeadWordsChild(e.Node, "t_Case_HeadWords");
        }
        public void t_Global_Court_AfterExpand(object sender, TreeViewEventArgs e)
        {
            e.Node.Nodes.Clear();
            GetTreeHeadWordsChild(e.Node, "t_Global_Court");
        }



        #endregion

        #region 左侧树
        /// <summary>
        /// 定位
        /// </summary>
        /// <param name="id"></param>
        private void ToLocateNode(string id)
        {
            var notePidArr = getregex.GetParseValue("CC1509171748560001", trbll.GetAllParentNode(id)).Split(',');//去掉多余逗号 ;
            for (var i = 0; i < notePidArr.Length; i++)
            {
                if (i != notePidArr.Length - 1)
                {
                    FindNode(notePidArr[i]).Expand();
                }
                else
                {
                    var node = FindNode(notePidArr[i]);
                    tVCaseCause.SelectedNode = node;
                }
            }
        }

        /// <summary>
        /// 案由树（第一级）
        /// </summary>
        public void CaseCauseTree()
        {
            #region 初始化
            tVCaseCause.Nodes.Clear();
            NodeList = new List<TreeNode>();
            MaxCount.Text = "";
            CurrentCount.Text = "";
            SkipNumber.Text = "";
            #endregion
            var dt = trbll.NodeTree_Tree("");//第一层的树
            var arrayDr = dt.Select("name='" + TypeName + "'");//找出“刑事罪名”的节点
            foreach (var caseTreeNodeRode in arrayDr)
            {
                var node = new TreeNode();
                node.Text = LdFormat.ObjectToString(caseTreeNodeRode[1]);
                node.Tag = caseTreeNodeRode[0];
                node.Name = LdFormat.ObjectToString(caseTreeNodeRode[2]);
                FirId = caseTreeNodeRode[0].ToString();
                if (trbll.NodeTree_Tree(node.Tag.ToString()).Rows.Count > 0)//节点有没有下级
                {
                    node.Nodes.Add(new TreeNode());
                }
                tVCaseCause.Nodes.Add(node);//父级节点添加节点
                if (caseTreeNodeRode["CC_CommonCase"].ToString() == "1" && ISCommonCase == 1)//同案节点标颜色
                    node.ForeColor = Color.Blue;
                NodeList.Add(node);//list用来查询
            }
            if (clicknode != null)
            { }
            else
            {
                if (tVCaseCause.Nodes.Count > 0)
                    tVCaseCause.SelectedNode = tVCaseCause.Nodes[0];
            }
        }
        /// <summary>
        /// 下级树
        /// </summary>
        /// <param name="parentNode"></param>
        private void CaseCauseTreeChild(TreeNode parentNode)
        {
            var pid = parentNode.Tag.ToString();// 父级ID
            var caseTreeNodeRode = trbll.NodeTree_Tree(pid);//父级ID的下级节点
            if (caseTreeNodeRode.Rows.Count == 0)
                return;
            for (var i = 0; i < caseTreeNodeRode.Rows.Count; i++)
            {
                var node = new TreeNode();
                node.Text = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["name"]);
                node.Tag = caseTreeNodeRode.Rows[i]["id"];
                node.Name = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["CC_NodeType"]);
                if (trbll.NodeTree_Tree(node.Tag.ToString()).Rows.Count > 0)//节点有无下级
                {
                    node.Nodes.Add(new TreeNode());
                }
                if (caseTreeNodeRode.Rows[i]["CC_CommonCase"].ToString() == "1" && ISCommonCase == 1)//同案节点标颜色
                    node.ForeColor = Color.Blue;
                parentNode.Nodes.Add(node);//父级节点添加节点
                TreeNode node1 = null;
                foreach (var node2 in NodeList)//遍历现在界面上的所有节点
                {
                    if (node2.Tag.ToString() == node.Tag.ToString())
                    {
                        node1 = node2;
                        break;
                    }
                }
                if (node1 != null)
                {
                    NodeList.Remove(node1);
                    NodeList.Add(node);//list用来查询
                }
                else
                {
                    NodeList.Add(node);
                }
            }
        }

        private void tVCaseCause_AfterExpand(object sender, TreeViewEventArgs e)
        {
            e.Node.Nodes.Clear();
            CaseCauseTreeChild(e.Node);
        }

        private void tVCaseCause_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (clicknode != null && clicknode.ForeColor != Color.Blue)
            {
                if (e.Node != null)
                {
                    if (clicknode.Text != e.Node.Text)
                    {
                        objCaseCause = casecausebLL.GetCaseCauseByCCID(clicknode.Tag.ToString());
                        if (objCaseCause != null && objCaseCause.CC_CommonCase == 1)
                        {
                            clicknode.ForeColor = Color.Blue;
                        }
                        else
                        {
                            clicknode.ForeColor = Color.Black;
                        }
                    }
                }
            }
            if (e.Node != null)
            {
                clicknode = e.Node;//保存节点
                                   //根据ccid控制添加子节点、同级节点菜单显示             
                                   // if (clicknode.ForeColor != Color.Blue)
                clicknode.ForeColor = Color.Red;
                //    ColorCommonCase_Click(nul);
                GetRightValue(e);//右侧信息展现
            }
            webBrowser1.Url = null;
            webBrowerUser1.LoadUrl("");
        }
        #endregion

        #region 民事刑事按钮（显示不同树）

        public void GetColor()
        {
            btnXS.BackColor = Color.White;
            btnMS.BackColor = Color.White;
            btnXZ.BackColor = Color.White;
            btnPC.BackColor = Color.White;
            btnZX.BackColor = Color.White;
            btnXZZF.BackColor = Color.White;
        }
        private void button8_Click(object sender, EventArgs e)
        {
            TypeName = "刑事罪名";
            GetColor();
            var sendButton = (Button)sender;
            if (sendButton != null)
                sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }
        private void button6_Click(object sender, EventArgs e)
        {
            TypeName = "民事案由";
            GetColor();
            var sendButton = (Button)sender;
            if (sendButton != null)
                sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }
        private void button5_Click(object sender, EventArgs e)
        {
            TypeName = "行政案由";
            GetColor();
            var sendButton = (Button)sender;
            if (sendButton != null)
                sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }
        private void button4_Click(object sender, EventArgs e)
        {
            TypeName = "赔偿案由";
            GetColor();
            var sendButton = (Button)sender;
            if (sendButton != null)
                sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }
        private void button7_Click(object sender, EventArgs e)
        {
            TypeName = "执行案由";
            GetColor();
            var sendButton = (Button)sender;
            if (sendButton != null)
                sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }

        /// <summary>
        /// 行政执法点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnXZZF_Click(object sender, EventArgs e)
        {
            TypeName = "行政执法";
            GetColor();
            btnXZZF.Focus();
            //var sendButton = (Button)sender;
            //if (sendButton != null)
            btnXZZF.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }
        #endregion

        #region 编辑案由树节点

        private TreeNode editnode;//点击获得当前节点
        /// <summary>
        /// 显示菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tVCaseCause_MouseDown(object sender, MouseEventArgs e)
        {
            var clickPoint = new Point(e.X, e.Y);
            editnode = tVCaseCause.GetNodeAt(clickPoint);
            if (editnode != null)//判断你点的是不是一个节点
            {
                if (editnode.Level == 0)
                {
                    添加同级ToolStripMenuItem.Visible = false;
                }
                else
                {
                    添加同级ToolStripMenuItem.Visible = true;
                }
                objCaseCause = casecausebLL.GetCaseCauseByCCID(editnode.Tag.ToString());
                if (objCaseCause != null && objCaseCause.CC_NodeType == 12 && objCaseCause.CC_Name != "属性")
                {
                    添加子节点ToolStripMenuItem1.Enabled = false;
                }
                else
                {
                    添加子节点ToolStripMenuItem1.Enabled = true;
                }
                editnode.ContextMenuStrip = contextMenuStrip1;
                if (editnode.Text == "行政执法")
                {
                    匹配关联违法行为ToolStripMenuItem.Visible = true;
                }
                else
                {
                    匹配关联违法行为ToolStripMenuItem.Visible = false;
                }

                tVCaseCause.SelectedNode = editnode;//选中这个节点
            }
        }

        /// <summary>
        /// 添加子节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 添加子节点ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (clicknode.FullPath.Substring(0, 4) == "民事案由")
            {
                if (users.Contains(Gvar.uo.m_displayName))
                {
                    AddNode();
                }
                else
                {
                    MessageBox.Show("该用户没有操作民事案由的权限");
                    return;
                }
            }
            else if (clicknode.FullPath.Substring(0, 4) == "行政执法")
            {
                if (userXZs.Contains(Gvar.uo.m_displayName))
                {
                    AddNode();
                }
                else
                {
                    MessageBox.Show("该用户没有操作行政执法的权限");
                    return;
                }
            }
            else
            {
                AddNode();
            }

        }

        /// <summary>
        /// 添加子节点方法
        /// </summary>
        private void AddNode()
        {
            if (!tabControl1.TabPages.Contains(tabPage_EditNode))
                tabControl1.TabPages.Add(tabPage_EditNode);
            tabControl1.Visible = true;
            tabControl1.SelectTab(tabPage_EditNode);
            NodeFrame.Visible = true;
            EidtNodeGroup.Text = "添加子节点";
            Pname.Text = editnode.Text;
            label5.Visible = false;
            CC_ID.Visible = false;
            Typedt = casecausebLL.GetCaseCauseType();
            NodeTypeList.DataSource = Typedt;
            NodeTypeList.DisplayMember = "CC_NodeTypeName";
            NodeTypeList.ValueMember = "CC_NodeType";
            NodeTypeList.SelectedValue = "2";
            if (objCaseCause != null && objCaseCause.CC_Name == "属性" && clicknode.FullPath.Substring(0, 4) == "民事案由")
            {
                NodeTypeList.SelectedValue = "12";
                NodeTypeList.Enabled = false;
            }
            else
            {
                NodeTypeList.Enabled = true;
            }
            if (NodeTypeList.SelectedValue.ToString() == "12" || NodeTypeList.SelectedValue.ToString() == "11")
            {
                NodeSubTypeList.Visible = true;
                label39.Visible = true;
            }
            else
            {
                NodeSubTypeList.Visible = false;
                label39.Visible = false;
            }
        }

        /// <summary>
        /// 添加同级节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 添加同级ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (clicknode.FullPath.Substring(0, 4) == "民事案由")
            {
                if (users.Contains(Gvar.uo.m_displayName))
                {
                    AddTongJiNode();
                }
                else
                {
                    MessageBox.Show("该用户没有操作民事案由的权限");
                    return;
                }
            }
            else if (clicknode.FullPath.Substring(0, 4) == "行政执法")
            {
                if (userXZs.Contains(Gvar.uo.m_displayName))
                {
                    AddTongJiNode();
                }
                else
                {
                    MessageBox.Show("该用户没有操作行政执法的权限");
                    return;
                }
            }
            else
            {
                AddTongJiNode();
            }
        }

        private void AddTongJiNode()
        {
            if (!tabControl1.TabPages.Contains(tabPage_EditNode))
                tabControl1.TabPages.Add(tabPage_EditNode);
            tabControl1.Visible = true;
            tabControl1.SelectTab(tabPage_EditNode);
            NodeFrame.Visible = true;
            EidtNodeGroup.Text = "添加同级节点";
            Pname.Text = editnode.Parent.Text;
            label5.Visible = false;
            CC_ID.Visible = false;
            Typedt = casecausebLL.GetCaseCauseType();
            NodeTypeList.DataSource = Typedt;
            NodeTypeList.DisplayMember = "CC_NodeTypeName";
            NodeTypeList.ValueMember = "CC_NodeType";
            NodeTypeList.SelectedValue = editnode.Name;
            if (objCaseCause != null && objCaseCause.CC_NodeType == 12 && objCaseCause.CC_Name != "属性" && clicknode.FullPath.Substring(0, 4) == "民事案由" && clicknode.Parent.Text == "属性")
            {
                NodeTypeList.SelectedValue = "12";
                NodeTypeList.Enabled = false;
            }
            else
            {
                NodeTypeList.Enabled = true;
            }
            if (NodeTypeList.SelectedValue.ToString() == "12" || NodeTypeList.SelectedValue.ToString() == "11")
            {
                NodeSubTypeList.Visible = true;
            }
            else
            {
                NodeSubTypeList.Visible = false;
            }
        }

        /// <summary>
        /// 全部展开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AllExpandMenuItem_Click(object sender, EventArgs e)
        {
            AllExpandNode(editnode.Tag.ToString());//展开全部
        }
        /// <summary>
        /// 展开全部
        /// </summary>
        /// <param name="pid"></param>
        private void AllExpandNode(string pid)
        {
            var findNode = FindNode(pid);
            if (findNode != null) findNode.ExpandAll();
        }

        #region 原有上移，下移代码
        private void 上移ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (editnode.PrevNode != null)
            {
                var previd = editnode.PrevNode.Tag.ToString();
                var nestid = editnode.Tag.ToString();
                casecausebLL.UpCaseCause_SeralNum(previd, nestid);
                MovUp(editnode);
            }
        }
        private void 下移ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (editnode.NextNode != null)
            {
                var previd = editnode.Tag.ToString();
                var nestid = editnode.NextNode.Tag.ToString();
                casecausebLL.UpCaseCause_SeralNum(previd, nestid);
                MovDown(editnode);
            }
        }
        private void MovUp(TreeNode objNode)
        {
            //----节点的向上移动   
            if (objNode != null)
            {
                var newnode = new TreeNode();
                //--------如果选中节点为最顶节点   
                if (objNode.Index == 0)
                {
                    //-------------   
                }
                else if (objNode.Index != 0)
                {
                    newnode = (TreeNode)objNode.Clone();
                    //-------------若选中节点为根节点   
                    if (objNode.Level == 0)
                    {
                        tVCaseCause.Nodes.Insert(objNode.PrevNode.Index, newnode);
                    }
                    //-------------若选中节点并非根节点   
                    else if (objNode.Level != 0)
                    {
                        objNode.Parent.Nodes.Insert(objNode.PrevNode.Index, newnode);
                    }
                    objNode.Remove();
                    objNode = newnode;
                }

            }
        }
        private void MovDown(TreeNode objNode)
        {
            //----节点的向下移动   
            if (objNode != null)
            {
                var newnode = new TreeNode();
                //-------------如果选中的是根节点   
                if (objNode.Level == 0)
                {
                    //---------如果选中节点为最底节点   
                    if (objNode.Index == tVCaseCause.Nodes.Count - 1)
                    {
                        //---------------   
                    }
                    //---------如果选中的不是最底的节点   
                    else
                    {
                        newnode = (TreeNode)objNode.Clone();
                        tVCaseCause.Nodes.Insert(objNode.NextNode.Index + 1, newnode);
                        objNode.Remove();
                        objNode = newnode;

                    }
                }
                //-------------如果选中节点不是根节点   
                else if (objNode.Level != 0)
                {
                    //---------如果选中最底的节点   
                    if (objNode.Index == objNode.Parent.Nodes.Count - 1)
                    {
                        //-----------   
                    }
                    //---------如果选中的不是最低的节点   
                    else
                    {
                        newnode = (TreeNode)objNode.Clone();
                        objNode.Parent.Nodes.Insert(objNode.NextNode.Index + 1, newnode);
                        objNode.Remove();
                        objNode = newnode;
                    }
                }

            }
        }
        #endregion

        /// <summary>
        /// 保存节点信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveNodeBtn_Click(object sender, EventArgs e)
        {
            try
            {
                Log.WriteLog("保存节点开始：");
                string ccId = string.Empty;
                var model = new SYS_CaseCause();
                string name = string.Empty;
                //是否是民事节点
                bool IsMsNode = false;
                if (clicknode.FullPath.StartsWith("民事案由"))
                {
                    IsMsNode = true;
                }

                #region 节点名称
                if (string.IsNullOrEmpty(Childname.Text) && Childname.Visible == true)
                {
                    MsgBox.Warn("名称不能为空！");
                    Childname.Focus();
                    return;
                }
                else if (string.IsNullOrEmpty(cmbName.Text) && cmbName.Visible == true)
                {
                    MsgBox.Warn("名称不能为空！");
                    cmbName.Focus();
                    return;
                }
                if (Childname.Visible == true)
                {
                    name = Childname.Text;
                }
                else if (cmbName.Visible == true)
                {
                    name = cmbName.Text;
                }
                Log.WriteLog("节点名称为：" + name);
                #endregion

                int i = 0;
                string str1 = string.Empty;

                //2017.11.06修改90域bug133 如果存在xml结构不能包含特殊字符，否则可以通过            
                SYS_CaseCause nowNode = casecausebLL.GetCaseCauseByCCID(clicknode.Tag.ToString());
                try
                {
                    #region 返回案由的xml
                    SYS_CaseCause caseCausexml1;
                    if (clicknode.Name.ToString() == "2")
                    {
                        caseCausexml1 = casecausebLL.GetCaseCauseByCCID(clicknode.Tag.ToString());
                        caseCausexml1.ElementXML = Getxml("SYS_CaseCause\\ElementXML", caseCausexml1.CC_ID);
                    }
                    else
                    {
                        caseCausexml1 = casecausebLL.IsParentRealation1(clicknode.Tag.ToString());
                        caseCausexml1.ElementXML = Getxml("SYS_CaseCause\\ElementXML", caseCausexml1.CC_ID);
                    }
                    #endregion

                    #region 判断名称是否包含特殊字符
                    if (!string.IsNullOrEmpty(caseCausexml1.ElementXML))
                    {
                        //如果添加节点的父节点即当前节点在XML中有此节点则需要判断特殊字符否则不进行判断
                        XmlDocument doc = new XmlDocument();
                        string xml = caseCausexml1.ElementXML.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @"");
                        doc.LoadXml(xml);
                        XmlAttributeCollection xa = doc.Attributes;
                        i = nowNode.AllParentName.LastIndexOf(caseCausexml1.CC_Name);
                        string xmlPath = nowNode.XmlPath;
                        //.AllParentName.Substring(i).Replace(",属性", "");
                        //string[] strs = xmlPath.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        //StringBuilder sb = new StringBuilder();
                        //foreach (var item in strs)
                        //{
                        //    sb.Append("/" + item);
                        //}
                        //string res1 = sb.ToString();
                        //if (!res1.Contains("，"))
                        //{
                        if (!string.IsNullOrEmpty(xmlPath))
                        {
                            XmlNode objxml = doc.SelectSingleNode(xmlPath);
                            if (objxml != null)
                            {
                                foreach (char c in name)
                                {
                                    if (!char.IsLetter(c) && !char.IsNumber(c))
                                    {
                                        MsgBox.Warn("名称不能包含特殊字符！");
                                        return;
                                    }
                                }
                            }
                        }
                        //}
                    }
                    #endregion
                }
                catch (Exception ex)
                {
                    Log.WriteLog("判断名称是否包含特殊字符报错：" + ex.Message);
                }
                Log.WriteLog("判断名称是否包含特殊字符结束：");


                //化学专业名词，不能改 3-氧-2-苯基丁腈四千克以上不满二十千克 任雪峰20190618要求
                #region 民事案由名称不能以数字开头或数字！
                if (IsMsNode)
                {
                    int tmp;
                    if (int.TryParse(name, out tmp) || char.IsDigit(name[0]))
                    {
                        MsgBox.Warn("名称不能以数字开头或数字！");
                        return;
                    }
                }
                Log.WriteLog("判断名称不能以数字开头或数字结束");
                #endregion

                if (EidtNodeGroup.Text == "添加子节点")
                {
                    Log.WriteLog("添加子节点开始:");
                    int addNodeType = 0;
                    int addNodeSubType = 0;
                    addNodeType = Convert.ToInt32(NodeTypeList.SelectedValue);
                    if (NodeTypeList.Text.Trim() != "裁判理由" && NodeTypeList.Text.Trim() != "裁判结果" && NodeSubTypeList.Visible)
                    {
                        addNodeSubType = Convert.ToInt32(NodeSubTypeList.SelectedValue);
                    }
                    //如果添加节点类型为xml属性则判断该节点下是否有属性节点，没有则创建属性节点，然后再添加该节点到属性节点下
                    #region 获取属性节点
                    if (Convert.ToInt32(NodeTypeList.SelectedValue) == 12 && name != "属性" && clicknode.Text != "属性")
                    {
                        //获取属性节点
                        string objProperty = casecausebLL.IsHaveProperty(clicknode.Tag.ToString());

                        if (string.IsNullOrEmpty(objProperty))
                        {

                            //创建属性节点
                            model.CC_ID = newid.JudgeDoc_CreateID("SYS_CaseCause");
                            model.CC_Name = "属性";
                            model.CC_ParentID = editnode.Tag.ToString();
                            model.CC_NodeType = 12;
                            model.AllParentId = nowNode.AllParentId + "," + model.CC_ID;
                            model.AllParentName = nowNode.AllParentName + "," + model.CC_Name;
                            model.HW_level = model.AllParentName.Split(',').Length;
                            model.CC_SerialNumb = 1;
                            caseCausexml = casecausebLL.IsParentRealation1(nowNode.CC_ID);
                            caseCausexml.ElementXML = Getxml("SYS_CaseCause\\ElementXML", caseCausexml.CC_ID);

                            //2021.3.8:经过和王巧凤确认 所有的节点都应该维护xmlpath，案由节点的话xmlpath为/金融借款合同纠纷 其他节点为以末级案由开始的路径比如：/金融借款合同纠纷/基本要素/担保人追偿权
                            if (!string.IsNullOrEmpty(caseCausexml.ElementXML))
                            {
                                str1 = model.AllParentName.ToString();
                                if (str1.Contains("案由要素"))
                                {
                                    i = str1.IndexOf("案由要素");
                                }
                                else
                                {
                                    i = str1.IndexOf(caseCausexml.CC_Name);
                                }
                                string str2 = string.Empty;
                                if (model.CC_Name == "属性")
                                {
                                    str2 = str1.Substring(i - 1).Replace(',', '/').Replace("/属性", "");
                                }
                                else
                                {
                                    str2 = str1.Substring(i - 1).Replace(',', '/').Replace("/属性/", "/@");
                                }
                                model.XmlPath = str2;
                            }
                            casecausebLL.AddPropertyUpdateSerialNum(model.CC_ParentID);
                            if (casecausebLL.AddSYS_CaseCause(model, Gvar.uo.m_displayName))
                            {
                                //添加成功属性节点
                                casecausebLL.CaseCauseUpdateAllPid(model.CC_ID);
                                var addnode = new TreeNode();
                                addnode.Tag = model.CC_ID;
                                addnode.Text = model.CC_Name;
                                addnode.Name = model.CC_NodeType.ToString();
                                //editnode.Nodes.Insert(0, addnode);
                                editnode.Nodes.Add(addnode);
                                editnode.Expand();
                                tVCaseCause.SelectedNode = tVCaseCause.SelectedNode.Nodes[0];

                                editnode = addnode;

                                model = new SYS_CaseCause();
                                nowNode = casecausebLL.GetCaseCauseByCCID(addnode.Tag.ToString());
                            }
                        }
                        else
                        {
                            nowNode = casecausebLL.GetCaseCauseByCCID(objProperty);
                        }
                    }
                    #endregion
                    Log.WriteLog("获取属性节点结束:");

                    #region 配置节点信息
                    Log.WriteLog("配置节点开始信息开始:");
                    model.CC_ID = newid.JudgeDoc_CreateID("SYS_CaseCause");
                    model.CC_Name = name.Replace("\r\n", "");
                    model.CC_ParentID = nowNode.CC_ID.ToString();
                    model.CC_NodeType = addNodeType;
                    model.CC_NodeSubType = addNodeSubType;
                    model.PIS_ShowName = txbPIS_ShowName.Text.Trim();



                    //    addNodeType;
                    //if (NodeTypeList.Text.Trim() != "裁判理由" && NodeTypeList.Text.Trim() != "裁判结果")
                    //{
                    //    model.CC_NodeSubType = Convert.ToInt32(NodeSubTypeList.SelectedValue);
                    //}
                    model.AllParentId = nowNode.AllParentId + "," + model.CC_ID;
                    model.AllParentName = nowNode.AllParentName + "," + model.CC_Name;
                    model.HW_level = model.AllParentName.Split(',').Length;
                    model.CC_IsProcessNode = CC_IsProcessNode_N.Checked ? 0 : 1;
                    model.CC_IsCombination = CC_IsCombination_N.Checked ? 0 : 1;
                    model.CC_CommonCase = CC_CommonCase.Checked ? 1 : 0;
                    model.CC_SerialNumb = casecausebLL.GetNodeChildSerialNumber(editnode.Tag.ToString());
                    if (panelBase.Visible == true)
                    {
                        model.CC_IsBasicElements = radBtnYes.Checked ? 1 : 0;
                    }
                    if (nowNode.CC_NodeType == 2)
                    {
                        caseCausexml = nowNode;
                        caseCausexml.ElementXML = Getxml("SYS_CaseCause\\ElementXML", caseCausexml.CC_ID);
                    }
                    else
                    {
                        caseCausexml = casecausebLL.IsParentRealation1(nowNode.CC_ID);
                        caseCausexml.ElementXML = Getxml("SYS_CaseCause\\ElementXML", caseCausexml.CC_ID);
                    }
                    if (!string.IsNullOrEmpty(caseCausexml.ElementXML))
                    {

                        str1 = model.AllParentName.ToString();
                        if (str1.Contains("案由要素"))
                        {
                            i = str1.IndexOf("案由要素");
                        }
                        else
                        {
                            i = str1.IndexOf(caseCausexml.CC_Name);
                        }
                        if (i != -1)
                        {
                            string str2 = string.Empty;
                            if (model.CC_Name == "属性")
                            {
                                str2 = str1.Substring(i - 1).Replace(',', '/').Replace("/属性", "");
                            }
                            else
                            {
                                str2 = str1.Substring(i - 1).Replace(',', '/').Replace("/属性/", "/@");
                            }
                            model.XmlPath = str2;
                        }
                        else
                        {
                            model.XmlPath = string.Empty;
                        }
                    }
                    Log.WriteLog("配置节点开始信息结束:");
                    #endregion

                    ccId = casecausebLL.Exists(model.CC_Name, model.CC_ParentID);
                    if (!string.IsNullOrEmpty(ccId))
                    {
                        MessageBox.Show("已存在相同名称的节点！");
                        return;
                    }
                    else
                    {
                        if (casecausebLL.AddSYS_CaseCause(model, Gvar.uo.m_displayName))
                        {
                            Log.WriteLog("添加节点成功:");

                            // casecausebLL.UpdateXmlPath(model.CC_ID);
                            //casecausebLL.CaseCauseUpdateAllPid(model.CC_ID);
                            //   editnode.Expand();
                            var addnode = new TreeNode();
                            addnode.Tag = model.CC_ID;
                            addnode.Text = model.CC_Name;
                            addnode.Name = model.CC_NodeType.ToString();
                            if (name != "属性" && Convert.ToInt32(NodeTypeList.SelectedValue) == 12 && clicknode.Text != "属性")
                            {
                                editnode.FirstNode.Nodes.Add(addnode);
                                editnode.FirstNode.Expand();
                            }
                            else
                            {
                                editnode.Nodes.Add(addnode);
                                editnode.Expand();
                            }
                            tVCaseCause.SelectedNode = addnode;

                            //tVCaseCause.SelectedNode = null;
                            Log.WriteLog("节点树添加节点成功:");
                            #region 节点树更新xml
                            if (nowNode.CC_NodeType == 11 || nowNode.CC_NodeType == 12)
                            {
                                SYS_CaseCause caseCausexml = casecausebLL.IsParentRealation1(model.CC_ID);
                                Log.WriteLog("节点树更新xml开始:ccid：" + model.CC_ID + " cc_parentid:" + model.CC_ParentID + " ccid:" + caseCausexml.CC_ID);
                                nowNode = casecausebLL.GetCaseCauseByCCID(model.CC_ParentID);
                                caseCausexml.ElementXML = Getxml("SYS_CaseCause\\ElementXML", caseCausexml.CC_ID);
                                if (!string.IsNullOrEmpty(caseCausexml.ElementXML))
                                {
                                    XmlDocument doc = new XmlDocument();
                                    string xml = caseCausexml.ElementXML.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @"");
                                    doc.LoadXml(xml);
                                    i = nowNode.AllParentName.LastIndexOf(caseCausexml.CC_Name);
                                    string xmlPath = nowNode.XmlPath;
                                    //.AllParentName.Substring(i).Replace(",属性", "");
                                    //string[] strs = xmlPath.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                                    //StringBuilder sb = new StringBuilder();
                                    //foreach (var item in strs)
                                    //{
                                    //    sb.Append("/" + item);
                                    //}
                                    //string res1 = sb.ToString();
                                    //if (!res1.Contains("，"))
                                    //{
                                    if (!string.IsNullOrEmpty(xmlPath))
                                    {
                                        XmlNode objxml = doc.SelectSingleNode(xmlPath);

                                        //if (model.CC_NodeType == 11)
                                        //{

                                        // }
                                        if (objxml != null)
                                        {
                                            if (name != "属性")
                                            {
                                                //9.4只有XML节点和XML属性才进行XML结构的修改
                                                if (model.CC_NodeType == 12)
                                                {
                                                    XmlElement objxml001 = (XmlElement)objxml;
                                                    objxml001.SetAttribute(model.CC_Name, "");
                                                }
                                                else if (model.CC_NodeType == 11)
                                                {
                                                    XmlElement objElement = doc.CreateElement(model.CC_Name);
                                                    objxml.AppendChild(objElement);
                                                }
                                                string res2 = FormatXML(doc.InnerXml.ToString());
                                                bool res = casecausebLL.UpdateElementXML(caseCausexml.CC_ID, res2);
                                                if (res)
                                                {
                                                    // MsgBox.OK("添加成功，查看请刷新节点树!");
                                                }
                                                else
                                                {
                                                    MsgBox.Err("更新xml结构失败！");
                                                }
                                            }
                                        }
                                    }
                                    //}
                                }
                                #endregion
                                Log.WriteLog("节点树更新xml结束:");
                            }

                        }
                    }
                }
                else if (EidtNodeGroup.Text == "添加同级节点")
                {
                    Log.WriteLog("添加同级节点开始:");
                    int addNodeType = 0;
                    int addNodeSubType = 0;
                    addNodeType = Convert.ToInt32(NodeTypeList.SelectedValue);
                    if (NodeTypeList.Text.Trim() != "裁判理由" && NodeTypeList.Text.Trim() != "裁判结果" && NodeSubTypeList.Visible)
                    {
                        addNodeSubType = Convert.ToInt32(NodeSubTypeList.SelectedValue);
                    }
                    string objProperty = string.Empty;
                    nowNode = casecausebLL.GetCaseCauseByCCID(clicknode.Parent.Tag.ToString());
                    //如果添加节点类型为xml属性则判断该节点下是否有属性节点，没有则创建属性节点，然后再添加该节点到属性节点下
                    #region 获取属性节点
                    if (Convert.ToInt32(NodeTypeList.SelectedValue) == 12 && name != "属性" && nowNode.CC_Name != "属性")
                    {
                        //获取属性节点
                        objProperty = casecausebLL.IsHaveProperty(clicknode.Parent.Tag.ToString());
                        if (string.IsNullOrEmpty(objProperty))
                        {

                            //创建属性节点
                            model.CC_ID = newid.JudgeDoc_CreateID("SYS_CaseCause");
                            model.CC_Name = "属性";
                            model.CC_ParentID = clicknode.Parent.Tag.ToString();
                            model.CC_NodeType = 12;
                            model.AllParentId = nowNode.AllParentId + "," + model.CC_ID;
                            model.AllParentName = nowNode.AllParentName + "," + model.CC_Name;
                            model.HW_level = model.AllParentName.Split(',').Length;
                            model.CC_SerialNumb = 1;
                            //if (model.CC_NodeType == 12 || model.CC_NodeType == 11)
                            //{
                            if (nowNode.CC_NodeType == 2)
                            {
                                caseCausexml = nowNode;
                                caseCausexml.ElementXML = Getxml("SYS_CaseCause\\ElementXML", caseCausexml.CC_ID);
                            }
                            else
                            {
                                caseCausexml = casecausebLL.IsParentRealation1(model.CC_ID);
                                caseCausexml.ElementXML = Getxml("SYS_CaseCause\\ElementXML", caseCausexml.CC_ID);
                            }
                            if (!string.IsNullOrEmpty(caseCausexml.ElementXML))
                            {
                                str1 = model.AllParentName.ToString();
                                if (str1.Contains("案由要素"))
                                {
                                    i = str1.IndexOf("案由要素");
                                }
                                else
                                {
                                    i = str1.IndexOf(caseCausexml.CC_Name);
                                }
                                string strPat = string.Empty;
                                if (model.CC_Name == "属性")
                                {
                                    strPat = str1.Substring(i - 1).Replace(',', '/').Replace("/属性", "");
                                }
                                else
                                {
                                    strPat = str1.Substring(i - 1).Replace(',', '/').Replace("/属性/", "/@");
                                }
                                model.XmlPath = strPat;
                            }
                            casecausebLL.AddPropertyUpdateSerialNum(model.CC_ParentID);
                            if (casecausebLL.AddSYS_CaseCause(model, Gvar.uo.m_displayName))
                            {
                                //添加成功属性节点
                                casecausebLL.CaseCauseUpdateAllPid(model.CC_ID);
                                // casecausebLL.UpdateXmlPath(model.CC_ID);
                                var addnode = new TreeNode();
                                addnode.Tag = model.CC_ID;
                                addnode.Text = model.CC_Name;
                                addnode.Name = model.CC_NodeType.ToString();
                                editnode.Parent.Nodes.Insert(0, addnode);
                                editnode.Parent.Expand();
                                nowNode = casecausebLL.GetCaseCauseByCCID(model.CC_ID);
                                model = new SYS_CaseCause();
                            }
                        }
                        else
                        {
                            nowNode = casecausebLL.GetCaseCauseByCCID(objProperty);
                        }
                    }
                    Log.WriteLog("获取属性节点结束:");
                    #endregion

                    #region 配置节点开始信息
                    Log.WriteLog("配置节点开始信息开始:");
                    model.CC_ID = newid.JudgeDoc_CreateID("SYS_CaseCause");
                    model.CC_Name = name.Replace("\r\n", "");
                    model.CC_ParentID = nowNode.CC_ID.ToString();
                    model.CC_NodeType = addNodeType;
                    model.CC_NodeSubType = addNodeSubType;
                    model.CC_IsProcessNode = CC_IsProcessNode_N.Checked ? 0 : 1;
                    model.CC_IsCombination = CC_IsCombination_N.Checked ? 0 : 1;
                    model.CC_CommonCase = CC_CommonCase.Checked ? 1 : 0;
                    model.CC_CommonCase = CC_CommonCase.Checked ? 1 : 0;
                    model.PIS_ShowName = txbPIS_ShowName.Text.Trim();

                    //if (NodeTypeList.Text.Trim() != "裁判理由" && NodeTypeList.Text.Trim() != "裁判结果" && NodeSubTypeList.Visible)
                    //{
                    //    model.CC_NodeSubType = Convert.ToInt32(NodeSubTypeList.SelectedValue);
                    //}
                    //int index1 = nowNode.AllParentId.LastIndexOf(nowNode.CC_ID);
                    model.AllParentId = nowNode.AllParentId + "," + model.CC_ID;
                    //int index2 = nowNode.AllParentName.LastIndexOf(nowNode.CC_Name);
                    model.AllParentName = nowNode.AllParentName + "," + model.CC_Name;
                    model.HW_level = model.AllParentName.Split(',').Length;
                    if (panelBase.Visible == true)
                    {
                        model.CC_IsBasicElements = radBtnYes.Checked ? 1 : 0;
                    }
                    model.CC_SerialNumb = casecausebLL.GetNodeChildSerialNumber(editnode.Parent.Tag.ToString());
                    //if (model.CC_NodeType == 12 || model.CC_NodeType == 11)
                    //{
                    caseCausexml = casecausebLL.IsParentRealation1(nowNode.CC_ID);
                    caseCausexml.ElementXML = Getxml("SYS_CaseCause\\ElementXML", caseCausexml.CC_ID);
                    if (!string.IsNullOrEmpty(caseCausexml.ElementXML))
                    {
                        //if (model.CC_Name == "属性")
                        //{
                        str1 = model.AllParentName.ToString();
                        if (str1.Contains("案由要素"))
                        {
                            i = str1.IndexOf("案由要素");
                        }
                        else
                        {
                            i = str1.IndexOf(caseCausexml.CC_Name);
                        }
                        string str2 = string.Empty;
                        if (model.CC_Name == "属性")
                        {
                            str2 = str1.Substring(i - 1).Replace(',', '/').Replace("/属性", "");
                        }
                        else
                        {
                            str2 = str1.Substring(i - 1).Replace(',', '/').Replace("/属性/", "/@");
                        }
                        model.XmlPath = str2;
                        //}
                    }
                    Log.WriteLog("配置节点开始信息结束:");
                    #endregion

                    ccId = casecausebLL.Exists(model.CC_Name, model.CC_ParentID);
                    if (!string.IsNullOrEmpty(ccId))
                    {
                        MessageBox.Show("已存在相同名称的节点！");
                        return;
                    }
                    else
                    {
                        if (casecausebLL.AddSYS_CaseCause(model, Gvar.uo.m_displayName))
                        {
                            Log.WriteLog("添加节点成功:");
                            casecausebLL.CaseCauseUpdateAllPid(model.CC_ID);
                            //casecausebLL.UpdateXmlPath(model.CC_ID);
                            var addnode = new TreeNode();
                            addnode.Tag = model.CC_ID;
                            addnode.Text = model.CC_Name;
                            addnode.Name = model.CC_NodeType.ToString();
                            //var index = editnode.Index;
                            //editnode.Parent.Nodes.Insert(index + 1, addnode);
                            //editnode.Parent.Nodes.Add(addnode);
                            //editnode.Parent.Expand();
                            if (name != "属性" && Convert.ToInt32(NodeTypeList.SelectedValue) == 12 && nowNode.CC_Name == "属性" && clicknode.Parent.Text != "属性")
                            {
                                //if (editnode.Parent.PrevNode.Text == "属性")
                                //{
                                editnode.Parent.Nodes[0].Nodes.Add(addnode);
                                editnode.Parent.Nodes[0].Expand();
                                //editnode.Parent.PrevNode.Nodes.Add(addnode);
                                //editnode.Parent.PrevNode.Expand();
                                //  }                               
                            }
                            else
                            {

                                editnode.Parent.Nodes.Add(addnode);
                                editnode.Parent.Expand();
                            }
                            tVCaseCause.SelectedNode = addnode;
                            Log.WriteLog("节点树添加节点成功:");

                            #region 节点树更新xml
                            if (nowNode.CC_NodeType == 11 || nowNode.CC_NodeType == 12)
                            {
                                SYS_CaseCause caseCausexml = casecausebLL.IsParentRealation1(model.CC_ID);
                                Log.WriteLog("节点树更新xml开始:ccid：" + model.CC_ID + "  ccid:" + caseCausexml.CC_ID);
                                caseCausexml.ElementXML = Getxml("SYS_CaseCause\\ElementXML", caseCausexml.CC_ID);
                                // nowNode = casecausebLL.GetCaseCauseByCCID(model.CC_ParentID);
                                if (!string.IsNullOrEmpty(caseCausexml.ElementXML))
                                {
                                    XmlDocument doc = new XmlDocument();
                                    string xml = caseCausexml.ElementXML.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @"");
                                    doc.LoadXml(xml);
                                    i = nowNode.AllParentName.LastIndexOf(caseCausexml.CC_Name);
                                    string xmlPath = nowNode.XmlPath;
                                    //nowNode.AllParentName.Substring(i).Replace(",属性", "");
                                    //string[] strs = xmlPath.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                                    //StringBuilder sb = new StringBuilder();
                                    //foreach (var item in strs)
                                    //{
                                    //    sb.Append("/" + item);
                                    //}
                                    //string res1 = sb.ToString();
                                    //if (!res1.Contains("，"))
                                    //{
                                    if (!string.IsNullOrEmpty(xmlPath))
                                    {
                                        XmlNode objxml = doc.SelectSingleNode(xmlPath);

                                        //if (model.CC_NodeType == 11)
                                        //{

                                        // }
                                        if (objxml != null)
                                        {
                                            if (name != "属性")
                                            {
                                                if (model.CC_NodeType == 12)
                                                {
                                                    XmlElement objxml001 = (XmlElement)objxml;
                                                    objxml001.SetAttribute(model.CC_Name, "");
                                                }
                                                else if (model.CC_NodeType == 11)
                                                {
                                                    XmlElement objElement = doc.CreateElement(model.CC_Name);
                                                    objxml.AppendChild(objElement);
                                                }
                                                string res2 = FormatXML(doc.InnerXml.ToString());
                                                bool res = casecausebLL.UpdateElementXML(caseCausexml.CC_ID, res2);
                                                if (res)
                                                {
                                                    // MsgBox.OK("添加成功，查看请刷新节点树!");
                                                }
                                                else
                                                {
                                                    MsgBox.Err("更新xml结构失败！");
                                                }
                                            }
                                        }
                                    }
                                    //}
                                }
                                Log.WriteLog("节点树更新xml结束:");
                                #endregion
                            }

                        }
                    }
                }
                //根据案由节点获取xmlPath
                //if (IsMsNode)
                //{
                casecausebLL.UpdateXmlPath(casecausebLL.IsParentRealation1(model.CC_ID).CC_ID);
                //}
                //else //刑事案由等其他案由
                //{
                //    casecausebLL.UpdateXmlPathByXS(casecausebLL.IsParentRealation1(model.CC_ID).CC_ID);
                //}
                MessageBox.Show("节点保存成功！");

            }
            catch (Exception error)
            {
                MsgBox.Err("节点保存失败！" + error.Message);
                Log.WriteLog(error.Message);

            }


            #region 清空节点信息
            ClearGroupEditNode();
            NodeFrame.Visible = false;
            if (tabControl1.TabPages.Contains(tabPage_EditNode))
                tabControl1.TabPages.Remove(tabPage_EditNode);
            #endregion

        }

        #region 清空节点信息框
        /// <summary>
        /// 清空节点信息框
        /// </summary>
        public void ClearGroupEditNode()
        {
            label5.Visible = false;
            CC_ID.Visible = false;
            EidtNodeGroup.Text = "";
            Pname.Text = "";
            Childname.Text = "";
            CC_IsCombination_N.Checked = true;
            CC_IsProcessNode_N.Checked = true;
            CC_CommonCase.Checked = false;
            NodeTypeList.SelectedValue = "2";
            panelBase.Visible = false;
            txbPIS_ShowName.Text = "";
        }
        #endregion

        /// <summary>
        /// 取消编辑节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            NodeFrame.Visible = false;
            if (tabControl1.TabPages.Contains(tabPage_EditNode))
                tabControl1.TabPages.Remove(tabPage_EditNode);
            ClearGroupEditNode();
        }


        #region 重新执行数据
        private void 删除ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (clicknode.FullPath.Substring(0, 4) == "民事案由")
            {
                if (users.Contains(Gvar.uo.m_displayName))
                {
                    DeleteNodes();
                }
                else
                {
                    MessageBox.Show("该用户没有操作民事案由的权限");
                    return;
                }
            }
            else if (clicknode.FullPath.Substring(0, 4) == "行政执法")
            {
                if (userXZs.Contains(Gvar.uo.m_displayName))
                {
                    DeleteNodes();
                }
                else
                {
                    MessageBox.Show("该用户没有操作行政执法的权限");
                    return;
                }
            }
            else
            {
                DeleteNodes();
            }
        }

        private void DeleteNodes()
        {
            if (MessageBox.Show("确认要删除节点" + editnode.Text + "及其子节点吗？", "此删除不可恢复", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    DataTable dt = xrsg.GetGroupCount(editnode.Tag.ToString());
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        StringBuilder sb = new StringBuilder();
                        foreach (DataRow dr in dt.Rows)
                        {
                            sb.Append(dr["CC_Name"] + ",");
                        }
                        if (sb.Length > 0)
                        {
                            MessageBox.Show("该情形:" + sb.ToString().Remove(sb.Length - 1, 1) + " 已被（组合）情形所引用，请先删除组合情形引用数据！");
                            return;
                        }
                    }
                    //SourceBLL.DeleteSourceByCC_ID(LdFormat.ObjectToString(clicknode.Tag));

                    //#region 查询条件
                    //conditonList.Clear();
                    //DataSourceCondition condi = new DataSourceCondition(); //条件
                    //condi.ISAgainData = true;
                    //condi.SituationId = editnode.Tag.ToString();
                    //conditonList.Add(condi);
                    //#endregion
                    //WorkThread workObj = WorkThreadFactory.CreateWorkThreadObj("second");
                    //workObj.processShow = ShowProgress;
                    //workObj.closeForm = CloseForm;
                    //workObj.conditonList = conditonList;
                    //workObj.execute();
                    try
                    {
                        SYS_CaseCause caseCausexml = casecausebLL.IsParentRealation1(editnode.Tag.ToString());
                        caseCausexml.ElementXML = Getxml("SYS_CaseCause\\ElementXML", caseCausexml.CC_ID);
                        if (!string.IsNullOrEmpty(caseCausexml.ElementXML))
                        {
                            XmlDocument doc = new XmlDocument();
                            string xml = caseCausexml.ElementXML.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @"");
                            doc.LoadXml(xml);
                            //int i = clicknode.FullPath.LastIndexOf(caseCausexml.CC_Name);
                            //clicknode.FullPath.Substring(i);
                            SYS_CaseCause caseCauseNode = casecausebLL.GetCaseCauseByCCID(editnode.Tag.ToString());
                            string res1 = caseCauseNode.XmlPath;
                            //GetXmlPath(clicknode.FullPath, caseCausexml.CC_Name);
                            //if (editnode.Text == "属性")
                            //{
                            //    xmlPath = xmlPath.Replace(",属性", "");
                            //}
                            //string[] strs = xmlPath.Split('\\');
                            //StringBuilder sb = new StringBuilder();
                            //foreach (var item in strs)
                            //{
                            //    sb.Append("/" + item);
                            //}
                            //string res1 = sb.ToString();

                            //XmlNodeList objXmlList = doc.SelectNodes(res1);
                            //if (objXmlList.Count > 0)
                            //{
                            if (!string.IsNullOrEmpty(res1))
                            {
                                if (clicknode.Name == "12")
                                {
                                    if (clicknode.Text != "属性")
                                    {
                                        int i1 = res1.LastIndexOf("/@");
                                        res1 = res1.Substring(0, i1);
                                    }

                                    XmlNode objxml = doc.SelectSingleNode(res1);
                                    if (objxml != null)
                                    {
                                        XmlElement objXml = (XmlElement)objxml;
                                        if (clicknode.Text != "属性")
                                        {
                                            objXml.RemoveAttribute(clicknode.Text);
                                        }
                                        else if (clicknode.Text == "属性")
                                        {
                                            objXml.RemoveAllAttributes();
                                        }
                                    }
                                }
                                else
                                {
                                    XmlNode objxml = doc.SelectSingleNode(res1);
                                    if (objxml != null)
                                    {
                                        XmlNode objParentXml = objxml.ParentNode;
                                        // XmlNodeList childNodes = objxml.ChildNodes;
                                        objParentXml.RemoveChild(objxml);
                                    }
                                }
                                string res2 = FormatXML(doc.InnerXml.ToString());
                                bool res = casecausebLL.UpdateElementXML(caseCausexml.CC_ID, res2);
                                if (res)
                                {
                                    // MsgBox.OK("添加成功，查看请刷新节点树!");
                                }
                                else
                                {
                                    MsgBox.Err("更新xml结构失败！");
                                }
                            }
                            // }
                            //foreach (var item in childNodes)
                            //{
                            //    XmlElement objxml1 = (XmlElement)item;
                            //    objxml1.RemoveAll();
                            //}
                            //XmlElement objElement = doc.CreateElement(model.CC_Name);
                            //objxml.AppendChild(objElement);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("维护xml结构出错：" + ex.Message);
                    }
                    string s = TypeName;
                    casecausebLL.DeleteSYS_CaseCause(editnode.Tag.ToString(), editnode.Text.ToString(), Gvar.uo.m_displayName);

                    if (TypeName == "刑事罪名")
                    {
                        eml.DeleteSys_ExpressAndWord(editnode.Tag.ToString());
                    }
                    MessageBox.Show("删除成功!");
                    if (editnode.Parent.Text == "属性" && editnode.Parent.Nodes.Count == 1)
                    {
                        tVCaseCause.Nodes.Remove(editnode.Parent);
                    }
                    else
                    {
                        tVCaseCause.Nodes.Remove(editnode);
                    }
                    // }
                }
                catch (Exception error)
                {
                    MessageBox.Show("删除失败!");
                }
            }
        }



        private void 重新执行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (editnode.Parent != null)
            {
                var dt = casecausebLL.GetSYS_CaseCauseByCCID(editnode.Parent.Tag.ToString());
                if (dt.Rows.Count > 0 && Convert.ToInt32(dt.Rows[0]["CC_IsProcessNode"]) > 0)//第一
                {
                    ConditionArr.Enabled = true;
                }
                else  //第二级
                {
                    ConditionArr.Enabled = false;
                }
            }
            else
            {
                ConditionArr.Enabled = false;
            }
            AgainCondition.Visible = true;
        }

        private void btn_AgainProcess_Click(object sender, EventArgs e)
        {
            #region 查询条件

            var condi = new DataSourceCondition(); //条件

            condi.HeadwordId = getregex.GetParseValue("CC1509241028190001", t_Case_HeadWords.Text.Trim());
            condi.JudicialProcedureId = getregex.GetParseValue("CC1509241028190001", t_Case_JudicialProcedure.Text.Trim());
            condi.PropertyId = getregex.GetParseValue("CC1509241028190001", t_Case_Property.Text.Trim());
            condi.ParagraphType = getregex.GetParseValue("CC1509241028190001", t_Case_ParagraphType.Text.Trim());
            condi.Court = getregex.GetParseValue("CC1509241028190001", t_Global_Court.Text.Trim());
            condi.SituationId = editnode.Tag.ToString();
            #endregion
            var workObj = new WorkThread_Second_Crime();                         //工作对象
            workObj.processShow = ShowProgress;
            workObj.closeForm = CloseForm;
            workObj.conditon = condi;
            workThread = new Thread(workObj.execute_Start);
            workThread.Start();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            t_Case_HeadWords.Text = "";
            t_Case_Property.Text = "";
            t_Case_JudicialProcedure.Text = "";
            t_Case_ParagraphType.Text = "";
            t_Global_Court.Text = "";
            progressBar1.Value = 0;
            lblCount.Text = "当前0条";
            AgainCondition.Visible = false;
        }

        /// <summary>
        /// 重新执行表述数据
        /// </summary>
        private void Reprogress()
        {
            //var AddElementDiction = new Dictionary<string, string>();//重加工数据
            //var dp = DataProcess.Default;
            //AddElementDiction.Add(editnode.Tag.ToString(), editnode.Text);
            //dp.Start_Again(AddElementDiction);
        }

        #region 查询节点
        DataTable Querydt;//查询结果集
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QueryNodeBtn_Click(object sender, EventArgs e)//查询
        {
            if (!string.IsNullOrEmpty(QueryNodeTxt.Text.Trim()))
            {
                switch (cmbCXFS.SelectedIndex)
                {
                    case 0:
                        QueryNode(QueryNodeTxt.Text.Trim());
                        break;
                    case 1:
                    case 2:
                    case 3:
                        string ccId = casecausebLL.GetCCIdBySearchCondition(QueryNodeTxt.Text.Trim(), cmbCXFS.SelectedIndex);
                        if (!string.IsNullOrEmpty(ccId))
                        {
                            QueryNode(ccId);
                        }
                        else
                        {
                            MessageBox.Show("没有查找到相应的数据！");
                        }
                        break;
                }
            }
            else
            {
                MessageBox.Show("请先输入需要查询的条件后再试！");
                QueryNodeTxt.Focus();
                return;
            }

        }
        /// <summary>
        /// 回车查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QueryNodeTxt_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')//回车
            {
                QueryNode(QueryNodeTxt.Text.Trim());
            }
        }

        /// <summary>
        /// 下一条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Nextlinkbtn_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (!string.IsNullOrEmpty(CurrentCount.Text))
            {
                CurrentCount.Text = (Convert.ToInt32(CurrentCount.Text) + 1).ToString();//下一条
                SkipNumber.Text = CurrentCount.Text;
                var CurrNode = Convert.ToInt32(CurrentCount.Text);
                QueryNode_Page(Querydt, CurrNode);//定位查询
                LinkIsVisible(CurrNode);
            }
        }
        /// <summary>
        /// 上一条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Prelinkbtn_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (!String.IsNullOrEmpty(CurrentCount.Text))
            {
                CurrentCount.Text = (Convert.ToInt32(CurrentCount.Text) - 1).ToString();//上一条
                SkipNumber.Text = CurrentCount.Text;
                var CurrNode = Convert.ToInt32(CurrentCount.Text);
                QueryNode_Page(Querydt, CurrNode);//定位查询
                LinkIsVisible(CurrNode);
            }
        }
        /// <summary>
        /// 上一条下一条是否可用
        /// </summary>
        /// <param name="CurrNode"></param>
        private void LinkIsVisible(int CurrNode)
        {
            Prelinkbtn.Enabled = true;
            Nextlinkbtn.Enabled = true;
            if (CurrNode <= 1)//当前小于1
            {
                Prelinkbtn.Enabled = false;//上一页不可用
            }
            if (CurrNode >= Querydt.Rows.Count)
            {
                Nextlinkbtn.Enabled = false;//下一页不可用
            }
        }
        /// <summary>
        /// 跳页查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GoQuery_Click(object sender, EventArgs e)
        {
            var CurrNode = Convert.ToInt32(SkipNumber.Text);//当前节点条数
            if (Querydt != null && !string.IsNullOrEmpty(QueryNodeTxt.Text.Trim()))
            {
                if (Querydt.Rows.Count >= CurrNode)
                {
                    CurrentCount.Text = SkipNumber.Text;//跳转
                    QueryNode_Page(Querydt, CurrNode);//定位到目标节点
                    LinkIsVisible(CurrNode);// 上一条下一条是否可用
                }
                else
                {
                    MessageBox.Show("跳转页码有误，重新输入！");
                }
            }
        }

        /// <summary>
        /// 查询定位节点方法
        /// </summary>
        /// <param name="queryText">查询条件</param>
        private void QueryNode(string queryText)
        {
            if (!string.IsNullOrEmpty(queryText))
            {
                Querydt = trbll.NodeTree_Query(FirId, queryText, 1);//查询结果
                MaxCount.Text = Querydt.Rows.Count.ToString();//总数
                if (Querydt.Rows.Count > 0)
                {
                    CurrentCount.Text = "1";//当前节点条数
                    SkipNumber.Text = CurrentCount.Text;//跳转文本框
                    var CurrNode = Convert.ToInt32(CurrentCount.Text);//当前节点条数
                    LinkIsVisible(CurrNode);//上一条下一条是否可用
                    QueryNode_Page(Querydt, CurrNode);//定位到目标节点
                }
                else
                {
                    CurrentCount.Text = "0";//没结果
                    SkipNumber.Text = CurrentCount.Text;
                    MessageBox.Show("没有查询到结果！");
                }
            }
            else
            {
                MessageBox.Show("请输入关键字！");
            }
        }


        /// <summary>
        /// 定位到目标节点
        /// </summary>
        /// <param name="dt">查询返回结果集</param>
        /// <param name="showindex">第几条</param>
        private void QueryNode_Page(DataTable dt, int showindex)
        {
            if (dt.Rows.Count >= showindex && showindex > 0)
            {
                var NotePidArr = trbll.GetAllParentNode(dt.Rows[showindex - 1]["id"].ToString()).Split(',');//所有父级
                for (var i = 0; i < NotePidArr.Length; i++)
                {
                    if (i != NotePidArr.Length - 1)
                    {
                        var Node = FindNode(NotePidArr[i]);
                        if (Node != null)
                        {
                            Node.Expand();//拖出所有父级节点
                        }
                        //TreeNode tnRet = null;
                        //foreach (TreeNode item in tVCaseCause.Nodes)
                        //{
                        //    tnRet = FindNodeByValue(item, NotePidArr[i].ToString());
                        //    if (tnRet != null) break;
                        //}
                        //if (tnRet != null)
                        //{
                        //    tnRet.Expand();
                        //}
                    }
                    else  //最后一级节点为查找节点
                    {
                        // tVCaseCause.ExpandAll();
                        var node = FindNode(NotePidArr[i]);

                        //TreeNode tnRet = null;
                        //foreach (TreeNode item in tVCaseCause.Nodes)
                        //{
                        //    tnRet = FindNodeByValue(item, NotePidArr[i].ToString());
                        //    if (tnRet != null) break;
                        //}
                        //// TreeNode[] obj = tVCaseCause.Nodes.Find(node.Text, true);
                        // tVCaseCause.SelectedNode = null;
                        tVCaseCause.SelectedNode = node;//定位          
                    }
                }
            }
            else
            {
                MessageBox.Show("跳转页码有误，重新输入！");
            }
        }


        /// <summary>
        /// 获取指定Text值的节点
        /// </summary>
        /// <param name="tnParent">指定节点</param>
        /// <param name="strValue">Text值</param>
        /// <returns></returns>
        private TreeNode FindNodeByText(TreeNode tnParent, string strText)
        {
            if (tnParent == null) return null;
            if (tnParent.Text == strText) return tnParent;

            TreeNode tnRet = null;
            foreach (TreeNode tn in tnParent.Nodes)
            {
                tnRet = FindNodeByText(tn, strText);
                if (tnRet != null) break;
            }
            return tnRet;
        }

        /// <summary>
        /// 获取指定value值的节点
        /// </summary>
        /// <param name="tnParent">指定节点</param>
        /// <param name="strValue">value值</param>
        /// <returns></returns>
        private TreeNode FindNodeByValue(TreeNode tnParent, string strValue)
        {
            if (tnParent == null) return null;
            if (tnParent.Tag.ToString() == strValue) return tnParent;

            TreeNode tnRet = null;
            foreach (TreeNode tn in tnParent.Nodes)
            {
                tnRet = FindNodeByValue(tn, strValue);
                if (tnRet != null) break;
            }
            return tnRet;
        }

        /// <summary>
        /// 查找节点
        /// </summary>
        /// <param name="Nodeid"></param>
        /// <returns></returns>
        private TreeNode FindNode(string Nodeid)
        {
            foreach (var node in NodeList)//遍历现在界面上的所有节点
            {
                if (node.Tag.ToString() == Nodeid)
                {
                    return node;
                }
            }
            return null;
            //return (TreeNode)NodeList[Nodeid];
        }

        #endregion

        #endregion

        #endregion

        #region 右侧
        #region     点击左边节点 显示右侧界面

        #region tabControl1
        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (tabControl1.SelectedTab.Name)
            {
                //诉请与要素关系配置插页  第十一个插页
                case "tab_XmlLabel_SuitTypeRel":
                    ShowSuitTypeList(clicknode.Tag.ToString());
                    break;
                //提取规则
                case "Tab_Extract":
                    ShowTab_Extract();
                    break;
                //推导规则
                case "Tab_Infer":
                    ShowTab_Infer();
                    break;
                //事实要素XML模板(第五个插页)
                case "tabPage_XML":
                    ShowXML();//显示XML
                    break;
                case "Tab_MatKeyWord":
                    ShowMatchKeyWord();//字典属性
                    break;
                case "Tab_ChooseXML":
                    ShowOptimizeXML();
                    break;
                case "tab_ArgumentTypeXml":
                    ShowArgumentTypeXml();
                    break;
                case "tab_AttrRelXML":
                    ShowAttrRelXML();
                    break;
                case "tabYaoSuZhengJuConfig":
                    ShowZhengJuList(clicknode.Tag.ToString());
                    break;
                case "tabFocusRelation":
                    ShowFocusList(clicknode.Tag.ToString());
                    break;
                //法定刑档次信息
                case "tabPageXF":
                    LoadFDXData();
                    break;
                case "tabPageFDXRelation":
                    GetFDXRelationInfo();
                    break;
                case "tabPageMDJF":
                    tabControl3.SelectedTab = tabPageFT;
                    tabControl3_SelectedIndexChanged(null, null);
                    tabControl4_SelectedIndexChanged(null, null);
                    break;
                case "tabXSXW":
                    ShowXSXWData();
                    break;
                case "tabPageGLXW":
                    ShowGLWFData();
                    break;
            }
        }



        /// <summary>
        /// 提取规则标签页
        /// </summary>
        private void ShowTab_Extract()
        {
            if (casecausebLL.IsCivilCase(clicknode.Tag.ToString()))
            {
                一键添加ToolStripMenuItem1.Enabled = true;
                if (clicknode.Name == "2" && casecausebLL.IsLastAnYou(clicknode.Tag.ToString()))
                {
                    btnRuleIn.Visible = btnRuleOut.Visible = true;
                }
                else
                {
                    btnRuleIn.Visible = btnRuleOut.Visible = false;
                }
            }
            else
            {
                一键添加ToolStripMenuItem1.Enabled = true;
                // 一键添加ToolStripMenuItem1.Enabled = false;
                btnRuleIn.Visible = btnRuleOut.Visible = false;
            }
            ShowSource(clicknode.Tag.ToString());//显示来源
            webBrowser1.Url = null;//正则
        }
        private void ShowTab_Infer()
        {
            ShowCondition(clicknode.Tag.ToString());//推导条件显示
            ShowInferRule(clicknode.Tag.ToString());//推导规则显示
            //LogExpreResult.Text = "";
            ClearAddCondition();
            //  HideAddCondi.Visible = false;
        }

        #endregion
        /// <summary>
        /// 显示
        /// </summary>
        /// <param name="e"></param>
        public void GetRightValue(TreeViewEventArgs e)
        {
            if (clicknode != null && !string.IsNullOrEmpty(clicknode.Name))
            {
                //类型等于案由或者附民要素时
                if ((Convert.ToInt32(clicknode.Name) == 2) || (Convert.ToInt32(clicknode.Name) == 23))//案由要显示XML
                {
                    if (!tabControl1.TabPages.Contains(tabPage_XML))
                    {
                        tabControl1.TabPages.Add(tabPage_XML);
                        // tabControl1.TabPages.Add(Tab_ChooseXML);
                        tabControl1.TabPages.Add(tab_ArgumentTypeXml);
                        // tabControl1.TabPages.Add(tab_AttrRelXML);
                    }
                    //todo by zhangpeng 2016-12-27 添加诉请与要素关系配置
                    if (!tabControl1.TabPages.Contains(tab_XmlLabel_SuitTypeRel))
                    {
                        tabControl1.TabPages.Add(tab_XmlLabel_SuitTypeRel);
                        ShowSuitTypeList(clicknode.Tag.ToString());
                    }

                    //if (!tabControl1.TabPages.Contains(tabYaoSuZhengJuConfig))
                    //{
                    //    tabControl1.TabPages.Add(tabYaoSuZhengJuConfig);
                    //    ShowZhengJuList(clicknode.Tag.ToString());
                    //}

                    //if (!tabControl1.TabPages.Contains(tabFocusRelation))
                    //{
                    //    tabControl1.TabPages.Add(tabFocusRelation);
                    //    ShowFocusList(clicknode.Tag.ToString());
                    //}
                }
                else
                {
                    if (tabControl1.TabPages.Contains(tabPage_XML))
                    {
                        tabControl1.TabPages.Remove(tabPage_XML);
                        // tabControl1.TabPages.Remove(Tab_ChooseXML);
                        tabControl1.TabPages.Remove(tab_ArgumentTypeXml);
                        //tabControl1.TabPages.Remove(tab_AttrRelXML);
                        tabControl1.TabPages.Remove(tabYaoSuZhengJuConfig);

                    }
                    if (tabControl1.TabPages.Contains(tab_XmlLabel_SuitTypeRel))
                    {
                        //todo by zhangpeng 2016-12-27 移除诉请与要素关系配置
                        tabControl1.TabPages.Remove(tab_XmlLabel_SuitTypeRel);
                    }
                    if (tabControl1.TabPages.Contains(tabYaoSuZhengJuConfig))
                    {
                        //todo by zhangpeng 2016-12-27 移除诉请与要素关系配置
                        tabControl1.TabPages.Remove(tabYaoSuZhengJuConfig);
                    }
                    //if (tabControl1.TabPages.Contains(tabFocusRelation))
                    //{
                    //    tabControl1.TabPages.Remove(tabFocusRelation);
                    //}
                }

                #region 加载矛盾纠纷业务加工页签
                if (ConfigHelper.AppSettings("Version") == "52" && dtMdjf.Select(" DS_CaseCauseID='" + clicknode.Tag.ToString() + "' ").Length == 1)
                {
                    if (!tabControl1.TabPages.Contains(tabPageMDJF))
                    {
                        tabControl1.TabPages.Add(tabPageMDJF);
                    }

                }
                else
                {
                    if (tabControl1.TabPages.Contains(tabPageMDJF))
                    {
                        tabControl1.TabPages.Remove(tabPageMDJF);
                    }
                }
                #endregion

                if ((clicknode.Name == "2") && clicknode.FullPath.Contains("刑事罪名") && clicknode.Text != "刑事罪名")
                {
                    if (!tabControl1.TabPages.Contains(tabPageXF))
                    {
                        tabControl1.TabPages.Add(tabPageXF);
                    }
                    if (!tabControl1.TabPages.Contains(tabPageFDXRelation))
                    {
                        tabControl1.TabPages.Add(tabPageFDXRelation);
                    }
                }
                else
                {
                    if (tabControl1.TabPages.Contains(tabPageXF))
                    {
                        tabControl1.TabPages.Remove(tabPageXF);
                    }
                    if (tabControl1.TabPages.Contains(tabPageFDXRelation))
                    {
                        tabControl1.TabPages.Remove(tabPageFDXRelation);
                    }
                }
                //有字典值的显示
                var matchValueCode = nodetree_argumenttypebll.IsExistMatchKeyWordCode(clicknode.Tag.ToString());

                //SYS_ArgumentTypeXml model = argumenttypexmlbll.GetModel(clicknode.Tag.ToString());
                if (matchValueCode != "" && !tabControl1.TabPages.Contains(Tab_MatKeyWord))
                {
                    tabControl1.TabPages.Add(Tab_MatKeyWord);
                }
                else if (matchValueCode == "" && tabControl1.TabPages.Contains(Tab_MatKeyWord))
                {
                    tabControl1.TabPages.Remove(Tab_MatKeyWord);
                }
                //编辑节点界面
                if (tabControl1.TabPages.Contains(tabPage_EditNode))
                    tabControl1.TabPages.Remove(tabPage_EditNode);

                //初始化第一个插页
                tabControl1.SelectedIndex = 0;
                tabControl1.Visible = true;

                ShowBaseProperty();
                //节点一级类型为Xml属性（除“属性”节点）不能添加下级节点；
                //if (objCaseCause != null && objCaseCause.CC_NodeType == 12 && objCaseCause.CC_Name != "属性")
                //{
                //    添加子节点ToolStripMenuItem1.Enabled = false;
                //}
                //else
                //{
                //    添加子节点ToolStripMenuItem1.Enabled = true;
                //}
                //节点类型为违法行为、违法情形展示相似违法行为
                if (Convert.ToInt32(clicknode.Name) == 29 || Convert.ToInt32(clicknode.Name) == 32)
                {
                    if (!tabControl1.TabPages.Contains(tabXSXW))
                    {
                        tabControl1.TabPages.Add(tabXSXW);
                        ShowXSXWData();
                    }
                }
                else
                {
                    tabControl1.TabPages.Remove(tabXSXW);
                }
                if (clicknode.Text == "行政执法")
                {
                    if (!tabControl1.TabPages.Contains(tabPageGLXW))
                    {
                        tabControl1.TabPages.Add(tabPageGLXW);
                        ShowGLWFData();
                    }
                }
                else
                {
                    tabControl1.TabPages.Remove(tabPageGLXW);
                }
                //裁量情节的子节点展示裁量情节与违法行为的配置信息
                if (clicknode.Parent != null && clicknode.Parent.Text == "裁量情节")
                {
                    grpXzzf_WfClRel.Visible = true;
                    TreeNodeCollection nodes = clicknode.Parent.Parent.Nodes;
                    string ccid = string.Empty;
                    foreach (TreeNode item in nodes)
                    {
                        if (item.Text == "违法行为")
                        {
                            ccid = item.Tag.ToString();
                            break;
                        }
                    }
                    if (!string.IsNullOrEmpty(ccid))
                    {
                        xzzfDisWfRelCxModels = new Xzzf_DisWfRelBLL().GetDisWfRelData(ccid);
                        if (xzzfDisWfRelCxModels.Any())
                        {
                            List<CommonComboxModel> districts = xzzfDisWfRelCxModels.Select(x => new CommonComboxModel { ComboxName = x.DistrictName, ComboxValue = x.CC_District }).ToList();
                            districts = districts.GroupBy(x => x.ComboxName).Select(x => x.First()).ToList();
                            cmbDistrict.DisplayMember = "ComboxName";
                            cmbDistrict.ValueMember = "ComboxValue";
                            cmbDistrict.DataSource = districts;
                        }
                    }
                    GetdgvWfClRelData();
                }
                else
                {
                    grpXzzf_WfClRel.Visible = false;
                }
            }
        }


        /// <summary>
        /// 清空当前节点
        /// </summary>
        public void ClearRightValue(TreeViewEventArgs e)
        {
            clicknode = null;
            tabControl1.Visible = false;
        }
        #endregion




        #region 来源规则（第一个插页）

        #region 来源树

        /// <summary>
        /// 第一级来源树+相关信息单元
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSource_Click(object sender, EventArgs e)
        {
            if (clicknode != null && clicknode.TreeView != null)
            {
                var frm = FrmInfoUnit.Instance;
                SYS_CaseCause objCause = casecausebLL.GetCaseCauseByCCID(clicknode.Tag.ToString());
                frm.CodeSubType = objCause.CC_NodeSubType.ToString();
                frm.CCNodeType = objCause.CC_NodeType.ToString();
                frm.ClickNode = clicknode;
                var dialogResult = frm.ShowDialog();
                if (dialogResult == DialogResult.Yes)
                {
                    ShowSource(clicknode.Tag.ToString());
                    frm.Close();
                    //frmDictEdit
                }
                ////加载节点类型列表
                //LoadCaseCouseListItem();

                //Sourceframe.Visible = true;
                //Tree_Source.Nodes.Clear();
                //SourceNodeList.Clear();

                ////DataTable dt = trbll.GetSourceTree(""); 修改查询表argument和argumenttype，转为SYS_CaseType_DocType和SYS_CaseType_DocType_LogicParag add by zhangpeng 2016-09-12 

                ////按照新需求，查询SYS_CaseType_DocType和SYS_CaseType_DocType_LogicParag表
                //DataTable dt = trbll.GetSourceTree_New("");
                //DataRow[] arrayDr = dt.Select();

                //foreach (DataRow caseTreeNodeRode in arrayDr)
                //{
                //    TreeNode node = new TreeNode();
                //    node.Text = LdFormat.ObjectToString(caseTreeNodeRode[2]);
                //    node.Tag = caseTreeNodeRode[0] + "," + caseTreeNodeRode[3];  //ID,Code

                //    if (trbll.GetSourceTreeChild(caseTreeNodeRode[0].ToString()).Rows.Count > 0)
                //    {
                //        node.Nodes.Add(new TreeNode());
                //    }

                //    Tree_Source.Nodes.Add(node);
                //    SourceNodeList.Add(node);
                //}

                ////信息来源（绑定的该节点已经建立的信息单元）
                //comboBox1.DataSource = regexbll.Relation_GetReg_EI_Code_Sql(clicknode.Tag.ToString());//设置数据源
                //comboBox1.DisplayMember = "InfoName";//设置显示列
                //comboBox1.ValueMember = "ids";//设置实际值
            }
        }


        /// <summary>
        /// 下级来源树
        /// </summary>
        /// <param name="parentNode">父节点</param>
        /// <param name="level">层级</param>
        private void BtnSourceTreeChild(TreeNode parentNode, int level)
        {
            var strArray = parentNode.Tag.ToString().Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);//ID,Code
            var pid = strArray[0];
            //DataTable caseTreeNodeRode = trbll.GetSourceTree(pid); //注释掉，不用ArgumentType和Argument表

            var caseTreeNodeRode = trbll.GetSourceTreeChild(pid, level + 1);
            if (caseTreeNodeRode.Rows.Count == 0)
                return;
            for (var i = 0; i < caseTreeNodeRode.Rows.Count; i++)
            {
                var node = new TreeNode();
                //node.Text = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["name"]);
                //node.Tag = caseTreeNodeRode.Rows[i]["id"];

                node.Text = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["CDL_Name"]);
                node.Tag = caseTreeNodeRode.Rows[i]["CDL_ID"] + "," + caseTreeNodeRode.Rows[i]["CDL_Code"];//ID,Code

                if (trbll.GetSourceTreeChild(LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["CDL_ID"]), level + 2).Rows.Count > 0)
                {
                    node.Nodes.Add(new TreeNode());
                }
                parentNode.Nodes.Add(node);
                SourceNodeList.Add(node);
            }
        }

        private void Tree_Source_AfterExpand(object sender, TreeViewEventArgs e)
        {
            e.Node.Nodes.Clear();
            BtnSourceTreeChild(e.Node, e.Node.Level);
        }
        #endregion

        #region 添加来源（单一）
        /// <summary>
        /// 添加来源（单一）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void AddSource_Click(object sender, EventArgs e)
        //{
        //    var i = SourceNodeList.Count(node => node.Checked);
        //    if (i == 0)
        //    {
        //        MsgBox.Warn("请先选择左边树节点");
        //        return;
        //    }
        //    //获取需要复制的信息单元，如果没有，则默认是新建信息单元
        //    var ids = comboBox1.SelectedValue.ToString();
        //    var ccRegexInfoCode = rbtnInfoNew.Checked ? string.Empty : ids.Split('-')[0];

        //    foreach (var node in SourceNodeList)
        //    {
        //        if (node.Checked)
        //        {
        //            var parentid = "";
        //            var parentName = "";
        //            var strArray = new string[] { };
        //            var sourceParaId = string.Empty;
        //            if (node.Level == 1)
        //            {
        //                parentName = node.Parent.Text;
        //                strArray = node.Parent.Tag.ToString().Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
        //                parentid = strArray[1];
        //            }
        //            else if (node.Level == 2)
        //            {
        //                parentName = node.Parent.Parent.Text;
        //                strArray = node.Parent.Parent.Tag.ToString().Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
        //                parentid = strArray[1];
        //            }
        //            else
        //            {
        //                parentName = node.Text;
        //                strArray = node.Tag.ToString().Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
        //                parentid = strArray[1];
        //            }
        //            sourceParaId =
        //                node.Tag.ToString().Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)[1];
        //            //if (node.Parent != null)
        //            //{
        //            //    parentName = node.Parent.Text;
        //            //    parentid = node.Parent.Tag.ToString();
        //            //}
        //            //else
        //            //{
        //            //    parentName = node.Text;
        //            //    parentid = node.Tag.ToString();
        //            //}
        //            if (!SourceBLL.Exists(clicknode.Tag.ToString(), parentid, sourceParaId)) //不存在
        //            {
        //                var model = new SysExpressSource();
        //                model.ES_ID = newid.JudgeDoc_CreateID("SYS_Express_Source");
        //                model.CC_ID = clicknode.Tag.ToString();

        //                model.Source_ID = parentid;

        //                model.Source_Name = parentName;
        //                model.Source_ParagraphID = sourceParaId;
        //                //model.Source_ParagraphID = node.Tag.ToString();
        //                model.Source_ParagraphName = node.Text;

        //                //正则不为空，则不需要添加信息来源，这里可以理解为为同一个节点添加信息来源，信息来源是一样的 todo by zhangpeng
        //                if (string.IsNullOrEmpty(ccRegexInfoCode))
        //                {
        //                    #region  信息单元
        //                    var nodeChild = new Model.Reg_InfoUnit();
        //                    nodeChild.EI_Name = clicknode.Text;
        //                    nodeChild.EN_ID = "EI_ID1507221438500001";
        //                    nodeChild.EI_Remark = "";
        //                    nodeChild.EI_ID = newid.CreateID("Reg_InfoUnit");
        //                    nodeChild.EI_Code = nodeChild.EI_ID;//编号==ID 
        //                    regexbll.AddReg_InfoUnit(nodeChild);
        //                    ccRegexInfoCode = nodeChild.EI_Code;
        //                    #endregion
        //                }
        //                model.CC_RegexInfoCode = ccRegexInfoCode;
        //                if (SourceBLL.AddSource(model))
        //                {
        //                    MsgBox.OK("添加成功!");
        //                }
        //                else
        //                {
        //                    MsgBox.Err("添加失败!");
        //                }
        //            }
        //            else
        //            {
        //                MsgBox.Warn("当前规则已存在!");
        //            }
        //        }
        //    }
        //    Sourceframe.Visible = false;
        //    rbtnInfoNew.Checked = true;
        //    ShowSource(clicknode.Tag.ToString());
        //}
        #endregion

        #region 批量添加来源
        /// <summary>
        /// 批量添加来源 add by zhangpeng
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void btn_batchAdd_Click(object sender, EventArgs e)
        //{
        //    var i = SourceNodeList.Count(node => node.Checked);
        //    if (i == 0)
        //    {
        //        MsgBox.Warn("请先选择左边树节点");
        //        return;
        //    }
        //    if (ddbChkType.Text == "请选择")
        //    {
        //        MsgBox.Warn("请选择批量添加的节点类型");
        //        return;
        //    }

        //    var ccNodeTypes = ddbChkType.CheckBoxItems.Where(x => x.CheckState == CheckState.Checked)
        //      .Select(x => int.Parse(((ComboxItem)x.ComboBoxItem).Value))
        //         .ToList();
        //    ////节点选择
        //    //if (rbtn_node.Checked)
        //    //{
        //    //    ccNodeTypes.Add((int)CcNodeType.XmlNode);
        //    //}
        //    ////属性选择
        //    //else if (rbtn_attr.Checked)
        //    //{
        //    //    ccNodeTypes.Add((int)CcNodeType.XmlAttr);
        //    //}
        //    //else // 节点和属性选择
        //    //{
        //    //    ccNodeTypes.Add((int)CcNodeType.XmlAttr);
        //    //    ccNodeTypes.Add((int)CcNodeType.XmlNode);
        //    //}
        //    var dialogResult = MsgBox.Ask("批量添加，即为当前节点及所有子节点或属性添加所选择的来源，确认操作？");
        //    if (dialogResult == DialogResult.Yes)
        //    {
        //        //获取需要复制的信息单元，如果没有，则默认是新建信息单元
        //        var ids = comboBox1.SelectedValue.ToString();
        //        var ccRegexInfoCode = rbtnInfoNew.Checked ? string.Empty : ids.Split('-')[0];
        //        var copySourceId = rbtnInfoNew.Checked ? string.Empty : ids.Split('-')[1];
        //        var copySourceParagraphId = rbtnInfoNew.Checked ? string.Empty : ids.Split('-')[2];
        //        //添加所有选择的来源节点
        //        var sysExpressSources = new List<SysExpressSource>();
        //        foreach (var node in SourceNodeList)
        //        {
        //            //节点选择
        //            if (node.Checked)
        //            {
        //                var parentid = "";
        //                var parentName = "";
        //                var strArray = new string[] { };
        //                var sourceParaId = string.Empty;
        //                if (node.Level == 1)
        //                {
        //                    parentName = node.Parent.Text;
        //                    strArray = node.Parent.Tag.ToString().Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
        //                    parentid = strArray[1];
        //                }
        //                else if (node.Level == 2)
        //                {
        //                    parentName = node.Parent.Parent.Text;
        //                    strArray = node.Parent.Parent.Tag.ToString().Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
        //                    parentid = strArray[1];
        //                }
        //                else
        //                {
        //                    parentName = node.Text;
        //                    strArray = node.Tag.ToString().Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
        //                    parentid = strArray[1];
        //                }

        //                sourceParaId =
        //                    node.Tag.ToString().Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)[1];
        //                if (!SourceBLL.Exists(clicknode.Tag.ToString(), parentid, sourceParaId)) //不存在
        //                {
        //                    var model = new SysExpressSource
        //                    {
        //                        ES_ID = newid.JudgeDoc_CreateID("SYS_Express_Source"),
        //                        CC_ID = clicknode.Tag.ToString(),
        //                        Source_ID = parentid,
        //                        Source_Name = parentName,
        //                        Source_ParagraphID = sourceParaId,
        //                        //Source_ParagraphID = node.Tag.ToString(),
        //                        Source_ParagraphName = node.Text
        //                    };

        //                    //正则不为空，则不需要添加信息来源，这里可以理解为为同一个节点添加信息来源，信息来源是一样的 todo by zhangpeng
        //                    if (ccRegexInfoCode == "")
        //                    {
        //                        #region  信息单元
        //                        var nodeChild = new Model.Reg_InfoUnit();
        //                        nodeChild.EI_Name = clicknode.Text;
        //                        nodeChild.EN_ID = "EI_ID1507221438500001";
        //                        nodeChild.EI_Remark = "";
        //                        nodeChild.EI_ID = newid.CreateID("Reg_InfoUnit");
        //                        nodeChild.EI_Code = nodeChild.EI_ID;//编号==ID 
        //                        regexbll.AddReg_InfoUnit(nodeChild);
        //                        ccRegexInfoCode = nodeChild.EI_Code;
        //                        #endregion
        //                    }
        //                    model.CC_RegexInfoCode = ccRegexInfoCode;
        //                    //添加节点
        //                    if (SourceBLL.AddSource(model))
        //                    {
        //                        //设置批量添加子节点的模型
        //                        var batchModel = new SysExpressSource
        //                        {
        //                            CC_ID = clicknode.Tag.ToString(),
        //                            Source_ID = parentid,
        //                            Source_Name = parentName,
        //                            //Source_ParagraphID = node.Tag.ToString(),
        //                            Source_ParagraphID = sourceParaId,
        //                            Source_ParagraphName = node.Text,
        //                            CC_RegexInfoCode = ccRegexInfoCode,

        //                            CopySourceId = copySourceId,
        //                            CopySourceParagraphId = copySourceParagraphId
        //                            //IsCopyRegex = true
        //                        };
        //                        sysExpressSources.Add(batchModel);

        //                        ////批量添加子节点
        //                        //if (SourceBLL.BatchAddSource(batchModel, ccNodeTypes))
        //                        //{
        //                        //    MsgBox.OK("批量添加成功!");
        //                        //}
        //                    }
        //                    else
        //                    {
        //                        MsgBox.Warn("添加失败!");
        //                        return;
        //                    }
        //                }
        //                else
        //                {
        //                    MsgBox.Warn("当前规则已存在!");
        //                    return;
        //                }
        //            }
        //        }
        //        //批量添加子节点和属性
        //        //if (SourceBLL.BatchAddSource(clicknode.Tag.ToString(), sysExpressSources, ccNodeTypes))
        //        //{
        //        //    MsgBox.OK("批量添加成功");
        //        //    //tran.Complete();
        //        //    Sourceframe.Visible = false;
        //        //    ShowSource(clicknode.Tag.ToString());
        //        //}
        //        //else
        //        //{
        //        //    MsgBox.Warn("批量添加失败！");
        //        //}
        //    }
        //    else
        //    {

        //        Sourceframe.Visible = false;
        //    }
        //    rbtnInfoNew.Checked = true;
        //}
        #endregion

        /// <summary>
        /// 取消来源
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void ClearSource_Click(object sender, EventArgs e)
        //{
        //    Sourceframe.Visible = false;
        //    rbtnInfoNew.Checked = true;
        //}

        /// <summary>
        /// 显示来源列表
        /// </summary>
        /// <param name="CC_ID"></param>
        private void ShowSource(string CC_ID)
        {
            GV_Source.AutoGenerateColumns = false;
            GV_Source.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            var dt = SourceBLL.GetSource(CC_ID);

            dt.Columns.Add("RelationSource", typeof(string));
            dt.Columns.Add("CheckRow", typeof(bool));

            for (var i = 0; i < dt.Rows.Count; i++)
            {
                dt.Rows[i][dt.Columns.Count - 2] = SourceBLL.GetRelationSource(dt.Rows[i]["CC_RegexInfoCode"].ToString(), dt.Rows[i]["ES_ID"].ToString());
                dt.Rows[i][dt.Columns.Count - 1] = false;
            }
            GV_Source.DataSource = dt;
        }

        /// <summary>
        /// 点击来源显示正则界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GV_Source_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                if (GV_Source.Rows[e.RowIndex].Cells["EI_ID"].Value != null)
                {
                    var EI_ID = GV_Source.Rows[e.RowIndex].Cells["EI_ID"].Value.ToString();
                    if (EI_ID != "")
                    {
                        Random rd = new Random();
                        webBrowser1.Url = new Uri(ConfigHelper.AppSettings("RegexSystemUrl") + "/RegexEdit.aspx?EIID=" + EI_ID + "&a=" + rd.Next(10000, 20000));

                        if (!string.IsNullOrEmpty(EI_ID))//修改
                        {
                            //区分案件要素中心和案由要素（1案件要素2案由要素）
                            string url = string.Format(ConfigHelper.AppSettings("ElementsRuleConfigPath") + "InformationUnit/InUn_MainList?Code={0}&userid={1}&ElemType=2 ", EI_ID, Gvar.uo.m_userId);
                            webBrowerUser1.LoadUrl(url);
                            //webBrowser1.ObjectForScripting = this;//2、设置js中window.external对象代表的类  
                        }
                    }
                    else
                    {
                        webBrowser1.Url = null;
                        webBrowerUser1.LoadUrl("");
                    }
                }
            }
            if (e.RowIndex == -1)
            {
                string revalue = this.GV_Source.Rows[0].Cells[0].EditedFormattedValue.ToString().ToLower();
                if (revalue == "false")
                {
                    for (int i = 0; i < GV_Source.Rows.Count; i++)
                    {
                        this.GV_Source.Rows[i].Cells[0].Value = "true";
                    }
                }
                else
                {
                    for (int i = 0; i < GV_Source.Rows.Count; i++)
                    {
                        this.GV_Source.Rows[i].Cells[0].Value = "false";
                    }
                }
                this.GV_Source.EndEdit();
            }
        }

        /// <summary>
        /// 删除来源
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_DeleteSource_Click(object sender, EventArgs e)
        {
            var DeleteES_ID = "";
            int num = 0;
            for (var i = 0; i <= GV_Source.Rows.Count - 1; i++)
            {
                var check = (DataGridViewCheckBoxCell)GV_Source.Rows[i].Cells["CheckRow"];
                if (Convert.ToBoolean(check.Value))
                {
                    num++;
                }
            }
            if (num == 0)
            {
                MsgBox.Warn("请勾选需要删除的数据后再试");
                return;
            }
            if (MessageBox.Show("确认要删除数据吗？", "此删除不可恢复", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    bool res = false;
                    for (var i = 0; i <= GV_Source.Rows.Count - 1; i++)
                    {
                        var check = (DataGridViewCheckBoxCell)GV_Source.Rows[i].Cells["CheckRow"];
                        if (Convert.ToBoolean(check.Value))
                        {
                            DeleteES_ID = GV_Source.Rows[i].Cells["ES_ID"].Value.ToString();
                            string purpose = GV_Source.Rows[i].Cells["ES_Purpose_Name"].Value.ToString();
                            string source = GV_Source.Rows[i].Cells["Source_Name"].Value.ToString();
                            string paragraphName = GV_Source.Rows[i].Cells["Source_ParagraphName"].Value.ToString();
                            if (DeleteES_ID != "")
                            {
                                res = SourceBLL.DeleteSource(DeleteES_ID);
                                Express_WordBLL wordbll = new Express_WordBLL();
                                wordbll.InsertDeleteLog("SYS_Express_Source", Frm.FrmLogin.userName, "提取规则界面删除数据，id为：" + DeleteES_ID + " 用途为：" + purpose + " 来源为: " + source + " 段落为:" + paragraphName + "  ccID:" + clicknode.Tag.ToString());

                            }
                        }
                    }
                    if (res)
                    {
                        MsgBox.OK("删除成功!");
                    }
                    else
                    {
                        MsgBox.Warn("删除失败!");
                    }
                }
                catch (Exception error)
                {
                    MsgBox.Warn("删除失败!");
                }

                ShowSource(clicknode.Tag.ToString());
            }
        }
        /// <summary>
        /// 独立化来源
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Independent_Click(object sender, EventArgs e)
        {

            for (var i = 0; i <= GV_Source.Rows.Count - 1; i++)
            {
                var check = (DataGridViewCheckBoxCell)GV_Source.Rows[i].Cells["CheckRow"];
                if (Convert.ToBoolean(check.Value))
                {
                    #region  新建信息单元
                    var nodeChild = new Model.Reg_InfoUnit();
                    nodeChild.EI_Name = clicknode.Text;
                    nodeChild.EN_ID = "EI_ID1507221438500001";
                    nodeChild.EI_Remark = "";
                    nodeChild.EI_ID = newid.CreateID("Reg_InfoUnit");
                    nodeChild.EI_Code = nodeChild.EI_ID;//编号==ID 
                    regexbll.AddReg_InfoUnit(nodeChild);

                    #endregion

                    #region 修改来源与信息单元的对应关系
                    var model = new SysExpressSource();
                    model.ES_ID = GV_Source.Rows[i].Cells["ES_ID"].Value.ToString();
                    model.CC_RegexInfoCode = nodeChild.EI_Code;
                    SourceBLL.Update(model);
                    #endregion

                    #region 复制原正则和关系

                    List<Reg_Regexs> regexs = regexbll.GetReg_RegexsByEiid(GV_Source.Rows[i].Cells["EI_ID"].Value.ToString());
                    List<Model.Reg_InfoRegexRelation> regRelations = regexbll.GetRegexRelationByEiid(GV_Source.Rows[i].Cells["EI_ID"].Value.ToString());
                    if (regexs.Count > 0 && regRelations.Count > 0)
                    {
                        for (int j = 0; j < regexs.Count; j++)
                        {
                            regexs[j].ER_ID = newid.CreateID("Reg_Regexs");
                            regexbll.InsertReg_Regexs(regexs[j]);
                            regRelations[j].EI_ID = nodeChild.EI_ID;
                            regRelations[j].ER_ID = regexs[j].ER_ID;
                            regRelations[j].ERR_ID = newid.CreateID("Reg_InfoRegexRelation");
                            regexbll.InsertRegex(regRelations[j]);
                        }
                    }


                    //var relation = unitrelation.GetListbyEI_ID(GV_Source.Rows[i].Cells["EI_ID"].Value.ToString());//原
                    //foreach (var item in relation)
                    //{
                    //    item.Reg_Regex.ER_ID = newid.CreateID("Reg_Regexs");
                    //    item.Reg_Regex.Reg_InfoRegexRelations = null;
                    //    item.Reg_Regex.Reg_Regexs1 = null;
                    //    item.Reg_Regex.Reg_Regexs2 = null;
                    //    addreg.Add(item.Reg_Regex);

                    //    item.ER_ID = item.Reg_Regex.ER_ID;
                    //    item.EI_ID = nodeChild.EI_ID;
                    //    item.Reg_Regex = null;
                    //    item.Reg_InfoUnit = null;
                    //    item.ERR_ID = newid.CreateID("Reg_InfoRegexRelation");

                    //    unitrelation.Add(item);

                    //}
                    #endregion            
                }
            }
            ShowSource(clicknode.Tag.ToString());
        }

        /// <summary>
        /// 选择新建
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void rbtnInfoNew_CheckedChanged(object sender, EventArgs e)
        //{
        //    if (rbtnInfoNew.Checked)
        //    {
        //        comboBox1.Enabled = false;
        //    }
        //    else
        //    {
        //        comboBox1.Enabled = true;
        //    }
        //}
        ///// <summary>
        ///// 选择共用
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void rbtnInfoCopy_CheckedChanged(object sender, EventArgs e)
        //{
        //    if (rbtnInfoCopy.Checked)
        //    {
        //        comboBox1.Enabled = true;
        //    }
        //    else
        //    {
        //        comboBox1.Enabled = false;
        //    }
        //}

        #endregion

        #region 推导规则(第二个插页)

        #region 推导规则

        /// <summary>
        /// 显示推导规则
        /// </summary>
        /// <param name="CC_ID"></param>
        private void ShowInferRule(string CC_ID)
        {
            //var dt = casecausebLL.GetSYS_CaseCauseByCCID(CC_ID);
            //EditSqlByCode.Text = LdFormat.ObjectToString(dt.Rows[0]["CC_InferRuleTextByCode"]);
        }

        /// <summary>
        /// 点击（and or not 等）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOperator_Click(object sender, EventArgs e)
        {
            var sendButton = (Button)sender;
            EditInferRule(sendButton.Text);
        }
        /// <summary>
        /// 编辑推导规则
        /// </summary>
        /// <param name="word"></param>
        private void EditInferRule(string word)
        {
            //var s = EditSqlByCode.Text;//光标处添加
            //var idx = EditSqlByCode.SelectionStart;
            //s = s.Insert(idx, word);
            //EditSqlByCode.Text = s;
            //EditSqlByCode.SelectionStart = idx + word.Length;
            //EditSqlByCode.Focus();
        }
        /// <summary>
        /// 保存推导规则
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveInferRule_Click(object sender, EventArgs e)
        {
            //try
            //{
            //    //#region 先测试
            //    //if (EditSqlByCode.Text.Trim() != "")
            //    //{
            //    //    string sql = getregex.GetParseValue("EI1510221424310001", EditSqlByCode.Text);
            //    //    List<string> LogicArr = analysisInferRule.InferRuleAllTest(sql);
            //    //    bool _Value = analysisInferRule.GetExpressionValue(LogicArr[0]);
            //    //}
            //    //#endregion
            //    if (casecausebLL.Update_CC_InferRuleText(EditSqlByCode.Text, clicknode.Tag.ToString()))//保存推断规则
            //    {
            //        MessageBox.Show("保存成功！");
            //    }
            //}
            //catch //(Exception error)
            //{
            //    MessageBox.Show("正则有误！");
            //}
        }

        /// <summary>
        /// 推导规则得到所有真值表结果
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void InferTest_Click(object sender, EventArgs e)
        {
            //try
            //{
            //    LogExpreResult.Text = "";
            //    var sql = getregex.GetParseValue("EI1510221424310001", EditSqlByCode.Text);//换成 ($ and $)
            //    var LogicArr = analysisInferRule.InferRuleAllTest(sql);//真值表
            //    bool _Value;
            //    foreach (var item in LogicArr)
            //    {
            //        _Value = analysisInferRule.GetExpressionValue(item);
            //        LogExpreResult.Text += item + ":" + Convert.ToInt32(_Value) + "\r\n";
            //    }
            //}
            //catch //(Exception error)
            //{
            //    MessageBox.Show("正则有误！");
            //}
        }

        #endregion

        #region 推导条件

        /// <summary>
        /// 显示推导条件
        /// </summary>
        /// <param name="CC_ID"></param>
        private void ShowCondition(string CC_ID)
        {
            //GV_InferCondition.AutoGenerateColumns = false;
            //GV_InferCondition.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            //var dt = infer.GetList(CC_ID);
            //GV_InferCondition.DataSource = dt;
        }

        /// <summary>
        /// 选择推导条件（用来组合推导规则）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ChooseCondi_Click(object sender, EventArgs e)
        {
            //var IR_Content = "";
            //for (var i = 0; i <= GV_InferCondition.Rows.Count - 1; i++)
            //{
            //    var check = (DataGridViewCheckBoxCell)GV_InferCondition.Rows[i].Cells["InferCondiCheck"];
            //    if (Convert.ToBoolean(check.Value))
            //    {
            //        IR_Content = "{" + GV_InferCondition.Rows[i].Cells["IR_Code"].Value + "}";

            //        if (IR_Content != "")
            //        {
            //            EditInferRule(IR_Content);
            //        }

            //    }
            //}
        }

        /// <summary>
        /// 保存推导条件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Save_InferCondition_Click(object sender, EventArgs e)
        {
            //var model = new SYSCaseCauseInferCondition();
            //model.IR_Name = txt_IR_Name.Text;
            //model.CC_ID = clicknode.Tag.ToString();
            //model.IR_Content = txt_IR_Content.Text;
            //model.IR_Remark = txt_IR_Remark.Text;
            //model.IR_Code = txt_IR_Code.Text;

            //if (HideIRID.Text.Trim() == "")//新建
            //{
            //    if (!infer.Exists(model))//编号唯一
            //    {
            //        model.IR_ID = newid.JudgeDoc_CreateID("SYS_CaseCause_InferCondition");
            //        if (infer.Add(model))
            //        {
            //            MessageBox.Show("保存成功!");
            //            ClearAddCondition();
            //            HideAddCondi.Visible = false;
            //        }
            //        else
            //        {
            //            MessageBox.Show("保存失败!");
            //        }
            //    }
            //    else
            //    {
            //        MessageBox.Show("编号已存在，请重新命名!");
            //    }
            //}
            //else //修改
            //{
            //    model.IR_ID = HideIRID.Text;
            //    if (infer.Update(model))
            //    {
            //        MessageBox.Show("保存成功!");
            //        ClearAddCondition();
            //        HideAddCondi.Visible = false;
            //    }
            //    else
            //    {
            //        MessageBox.Show("保存失败!");
            //    }
            //}
            //ShowCondition(model.CC_ID);
        }

        /// <summary>
        /// 添加（弹出推导条件编辑框）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CondiAdd_Click(object sender, EventArgs e)
        {
            //ClearAddCondition();
            //HideAddCondi.Visible = true;
        }

        /// <summary>
        /// 清空推导条件
        /// </summary>
        private void ClearAddCondition()
        {
            //txt_IR_Name.Text = "";
            //txt_IR_Code.Text = "";
            //txt_IR_Code.Enabled = true;
            //txt_IR_Remark.Text = "";
            //txt_IR_Content.Text = "";
            //HideIRID.Text = "";


        }

        /// <summary>
        /// 修改推导条件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GV_InferCondition_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //if (e.ColumnIndex != 0)  //编辑文本
            //{
            //    var IR_ID = GV_InferCondition.Rows[e.RowIndex].Cells["IR_ID"].Value.ToString();
            //    if (IR_ID != "")
            //    {
            //        var dt = infer.GetOneData(IR_ID);
            //        if (dt.Rows.Count > 0)
            //        {
            //            txt_IR_Name.Text = dt.Rows[0]["IR_Name"].ToString();
            //            txt_IR_Code.Text = dt.Rows[0]["IR_Code"].ToString();
            //            txt_IR_Code.Enabled = false;
            //            txt_IR_Remark.Text = dt.Rows[0]["IR_Remark"].ToString();
            //            txt_IR_Content.Text = dt.Rows[0]["IR_Content"].ToString();
            //            HideIRID.Text = IR_ID;
            //            HideAddCondi.Visible = true;
            //        }

            //    }
            //}

        }

        /// <summary>
        /// 删除推导条件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CondiDele_Click(object sender, EventArgs e)
        {
            //var DeleteIR_ID = "";
            //if (MessageBox.Show("确认要删除数据吗？", "此删除不可恢复", MessageBoxButtons.YesNo) == DialogResult.Yes)
            //{
            //    try
            //    {
            //        for (var i = 0; i <= GV_InferCondition.Rows.Count - 1; i++)
            //        {
            //            var check = (DataGridViewCheckBoxCell)GV_InferCondition.Rows[i].Cells["InferCondiCheck"];
            //            if (Convert.ToBoolean(check.Value))
            //            {
            //                DeleteIR_ID = GV_InferCondition.Rows[i].Cells["IR_ID"].Value.ToString();
            //                if (DeleteIR_ID != "")
            //                {
            //                    infer.Delete(DeleteIR_ID);
            //                }

            //            }
            //        }
            //        MessageBox.Show("删除成功!");
            //    }
            //    catch //(Exception error)
            //    {
            //        MessageBox.Show("删除失败!");
            //    }
            //    ShowCondition(clicknode.Tag.ToString());

            //}

        }

        #endregion




        #endregion

        #region 事实要素XML模板(第五个插页)

        private void ShowXML()
        {
            txtXML.Text = string.Empty;
            if (casecausebLL.IsLastAnYou(clicknode.Tag.ToString()) && casecausebLL.IsCivilCase(clicknode.Tag.ToString()))
            {
                btnUpdateNodeType.Visible = true;
            }
            else
            {
                btnUpdateNodeType.Visible = false;
            }
            string xml = Getxml("SYS_CaseCause\\ElementXML", clicknode.Tag.ToString());
            if (!string.IsNullOrEmpty(xml))
            {
                txtXML.Text = xml;
            }

            //string webapiUrl1 = ConfigHelper.AppSettings("xmlPath") + "/system/config/v1/getfilecontent";
            //RequestContent rc = new RequestContent() { systemName = "Ldt_JudgeDocSystem", moudleName = "SYS_CaseCause\\ElementXML", fileType = "xml", fileName = clicknode.Tag.ToString() };
            //ComResult model = WebUtil.DoPost<ComResult>(webapiUrl1, rc, "UTF-8");
            //if (model.result.code == "1")
            //{
            //    txtXML.Text = model.body.content;
            //    //var dt = casecausebLL.GetSYS_CaseCauseByCCID(clicknode.Tag.ToString());
            //    //LdFormat.ObjectToString(dt.Rows[0]["ElementXML"]);
            //}
        }

        /// <summary>
        /// 返回xml
        /// </summary>
        /// <param name="moudleName"></param>
        /// <param name="ccID"></param>
        /// <returns></returns>
        public string Getxml(string moudleName, string ccID)
        {
            string webapiUrl1 = ConfigHelper.AppSettings("xmlPath") + "/system/config/v1/getfilecontent";
            RequestContent rc = new RequestContent() { systemName = ConfigHelper.AppSettings("getXml"), moudleName = moudleName, fileType = "xml", fileName = ccID };
            ComResult model = WebUtil.DoPost<ComResult>(webapiUrl1, rc, "UTF-8");
            if (model.result.code == "1")
            {
                return model.body.content;
            }
            else
            {
                return string.Empty;
            }
        }



        private void SaveXML_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtXML.Text.Trim() != "")
                {
                    this.Cursor = Cursors.WaitCursor;
                    lblTS.Text = "正在解析xml并添加节点，请勿退出，耐心等待......";
                    Task.Run(() =>
                    {
                        //当前节点没有配置xml或者xml中第一级节点在树中不存在可以添加
                        XmlDocument document1 = new XmlDocument();
                        document1.LoadXml(txtXML.Text.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @""));
                        DataTable dtNodes = casecausebLL.GetNodeTree(clicknode.Tag.ToString());
                        SYS_CaseCause caseCause = casecausebLL.GetCaseCauseByCCID(clicknode.Tag.ToString());
                        string ccID = string.Empty;
                        if (document1.DocumentElement.Name == "案由要素")
                        {
                            //不包含案由要素则添加案由要素
                            if (dtNodes.Rows.Count == 0 || dtNodes.Select(" CC_Name='案由要素' ").Length == 0)
                            {
                                var model = new SYS_CaseCause();
                                model.CC_ID = newid.JudgeDoc_CreateID("SYS_CaseCause");
                                model.CC_Name = "案由要素";
                                model.CC_ParentID = clicknode.Tag.ToString();
                                model.CC_NodeType = 11;
                                model.PIS_ShowName = "案由要素";
                                model.AllParentId = caseCause.AllParentId + "," + model.CC_ID;
                                model.AllParentName = caseCause.AllParentName + "," + model.CC_Name;
                                model.HW_level = model.AllParentName.Split(',').Length;
                                model.CC_IsProcessNode = 0;
                                model.CC_IsCombination = 0;
                                model.CC_CommonCase = 0;
                                model.CC_SerialNumb = 0;
                                model.XmlPath = "/" + model.CC_Name;
                                string ccIdNew = casecausebLL.Exists(model.CC_Name, model.CC_ParentID);
                                if (!string.IsNullOrEmpty(ccIdNew))
                                {
                                    ccID = ccIdNew;
                                    DataTable dt = casecausebLL.GetCriminalNodes(ccIdNew);
                                    if (dt != null && dt.Rows.Count > 0)
                                    {
                                        if (dt.Select(" CC_Name= '案由名称'").Length == 0 && dt.Select(" CC_Name= '属性'").Length == 0)
                                        {
                                            string ccid = ccIdNew;
                                            string allParentName = model.AllParentName;
                                            string allParentId = model.AllParentId;
                                            string ccName = model.CC_Name;

                                            var model0 = new SYS_CaseCause();
                                            model0.CC_ID = newid.JudgeDoc_CreateID("SYS_CaseCause");
                                            model0.CC_Name = "属性";
                                            model0.CC_ParentID = ccid;
                                            model0.CC_NodeType = 12;
                                            model0.AllParentId = allParentId + "," + model0.CC_ID;
                                            model0.AllParentName = allParentName + "," + model0.CC_Name;
                                            model0.HW_level = model0.AllParentName.Split(',').Length;
                                            model0.CC_IsProcessNode = 0;
                                            model0.CC_IsCombination = 0;
                                            model0.CC_CommonCase = 0;
                                            model0.CC_SerialNumb = 0;
                                            model0.XmlPath = model.XmlPath;
                                            if (casecausebLL.AddSYS_CaseCause(model0, "syb"))
                                            {
                                                var model1 = new SYS_CaseCause();
                                                model1.CC_ID = newid.JudgeDoc_CreateID("SYS_CaseCause");
                                                model1.CC_Name = "案由名称";
                                                model1.CC_ParentID = model0.CC_ID;
                                                model1.CC_NodeType = 12;
                                                model1.AllParentId = model0.AllParentId + "," + model1.CC_ID;
                                                model1.AllParentName = model0.AllParentName + "," + model1.CC_Name;
                                                model1.HW_level = model1.AllParentName.Split(',').Length;
                                                model1.CC_IsProcessNode = 0;
                                                model1.CC_IsCombination = 0;
                                                model1.CC_CommonCase = 0;
                                                model1.CC_SerialNumb = 0;
                                                model1.XmlPath = model0.XmlPath + "/@案由名称";

                                                var model2 = new SYS_CaseCause();
                                                model2.CC_ID = newid.JudgeDoc_CreateID("SYS_CaseCause");
                                                model2.CC_Name = "案由ID";
                                                model2.CC_ParentID = model0.CC_ID;
                                                model2.CC_NodeType = 12;
                                                model2.AllParentId = model0.AllParentId + "," + model2.CC_ID;
                                                model2.AllParentName = model0.AllParentName + "," + model2.CC_Name;
                                                model2.HW_level = model2.AllParentName.Split(',').Length;
                                                model2.CC_IsProcessNode = 0;
                                                model2.CC_IsCombination = 0;
                                                model2.CC_CommonCase = 0;
                                                model2.CC_SerialNumb = 1;
                                                model2.XmlPath = model0.XmlPath + "/@案由ID";

                                                casecausebLL.AddSYS_CaseCause(model1, "syb");
                                                casecausebLL.AddSYS_CaseCause(model2, "syb");
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    ccID = model.CC_ID;
                                    if (casecausebLL.AddSYS_CaseCause(model, "syb"))
                                    {
                                        string ccid = model.CC_ID;
                                        string allParentName = model.AllParentName;
                                        string allParentId = model.AllParentId;
                                        string ccName = model.CC_Name;

                                        var model0 = new SYS_CaseCause();
                                        model0.CC_ID = newid.JudgeDoc_CreateID("SYS_CaseCause");
                                        model0.CC_Name = "属性";
                                        model0.CC_ParentID = ccid;
                                        model0.CC_NodeType = 12;
                                        model0.AllParentId = allParentId + "," + model0.CC_ID;
                                        model0.AllParentName = allParentName + "," + model0.CC_Name;
                                        model0.HW_level = model0.AllParentName.Split(',').Length;
                                        model0.CC_IsProcessNode = 0;
                                        model0.CC_IsCombination = 0;
                                        model0.CC_CommonCase = 0;
                                        model0.CC_SerialNumb = 0;
                                        model0.XmlPath = model.XmlPath;
                                        if (casecausebLL.AddSYS_CaseCause(model0, "syb"))
                                        {
                                            var model1 = new SYS_CaseCause();
                                            model1.CC_ID = newid.JudgeDoc_CreateID("SYS_CaseCause");
                                            model1.CC_Name = "案由名称";
                                            model1.CC_ParentID = model0.CC_ID;
                                            model1.CC_NodeType = 12;
                                            model1.AllParentId = model0.AllParentId + "," + model1.CC_ID;
                                            model1.AllParentName = model0.AllParentName + "," + model1.CC_Name;
                                            model1.HW_level = model1.AllParentName.Split(',').Length;
                                            model1.CC_IsProcessNode = 0;
                                            model1.CC_IsCombination = 0;
                                            model1.CC_CommonCase = 0;
                                            model1.CC_SerialNumb = 0;
                                            model1.XmlPath = model0.XmlPath + "/@案由名称";

                                            var model2 = new SYS_CaseCause();
                                            model2.CC_ID = newid.JudgeDoc_CreateID("SYS_CaseCause");
                                            model2.CC_Name = "案由ID";
                                            model2.CC_ParentID = model0.CC_ID;
                                            model2.CC_NodeType = 12;
                                            model2.AllParentId = model0.AllParentId + "," + model2.CC_ID;
                                            model2.AllParentName = model0.AllParentName + "," + model2.CC_Name;
                                            model2.HW_level = model2.AllParentName.Split(',').Length;
                                            model2.CC_IsProcessNode = 0;
                                            model2.CC_IsCombination = 0;
                                            model2.CC_CommonCase = 0;
                                            model2.CC_SerialNumb = 1;
                                            model2.XmlPath = model0.XmlPath + "/@案由ID";

                                            casecausebLL.AddSYS_CaseCause(model1, "syb");
                                            casecausebLL.AddSYS_CaseCause(model2, "syb");
                                        }
                                    }
                                }
                            }
                            else
                            {
                                ccID = dtNodes.Select(" CC_Name='案由要素' ")[0]["CC_ID"].ToString();
                            }
                        }
                        XmlElement xmlGen = document1.DocumentElement;
                        XmlNodeList nodesList = xmlGen.ChildNodes;
                        foreach (XmlNode item in nodesList)
                        {
                            if (document1.DocumentElement.Name == "案由要素")
                            {
                                if (dtNodes == null || dtNodes.Rows.Count == 0 || (dtNodes.Rows.Count > 0 && dtNodes.Select(" CC_Name='" + item.Name + "' ").Length == 0))
                                {
                                    var model = new SYS_CaseCause();
                                    model.CC_ID = newid.JudgeDoc_CreateID("SYS_CaseCause");
                                    model.CC_Name = item.Name;
                                    model.CC_ParentID = ccID;
                                    model.CC_NodeType = 11;
                                    model.PIS_ShowName = item.Name;
                                    model.AllParentId = caseCause.AllParentId + "," + ccID + "," + model.CC_ID;
                                    model.AllParentName = caseCause.AllParentName + ",案由要素," + model.CC_Name;
                                    model.HW_level = model.AllParentName.Split(',').Length;
                                    model.CC_IsProcessNode = 0;
                                    model.CC_IsCombination = 0;
                                    model.CC_CommonCase = 0;
                                    model.CC_SerialNumb = 0;
                                    model.XmlPath = "/案由要素/" + model.CC_Name;
                                    if (casecausebLL.AddSYS_CaseCause(model, "syb"))
                                    {
                                        XmlNodeList list = document1.GetElementsByTagName(item.Name);
                                        if (list.Count > 0)
                                        {
                                            analysisXML.AnalyAddXMLNodeNew(list, model.CC_ID, model.XmlPath, Gvar.uo.m_displayName);
                                        }
                                    }
                                    string nodeSubType = string.Empty;
                                    if (item.Name == "诉请要素")
                                    {
                                        nodeSubType = "18";
                                    }
                                    else if (item.Name == "事实要素")
                                    {
                                        nodeSubType = "19";
                                    }
                                    else if (item.Name == "基本要素")
                                    {
                                        nodeSubType = "20";
                                    }
                                    else if (item.Name == "结果要素")
                                    {
                                        nodeSubType = "24";
                                    }
                                    if (!string.IsNullOrEmpty(nodeSubType))
                                    {
                                        casecausebLL.UpdateCCNodeSubTypes(model.CC_ID, nodeSubType);
                                    }
                                }
                            }
                            else
                            {
                                XmlNodeList list = document1.GetElementsByTagName(item.Name);
                                if (list.Count > 0)
                                {
                                    analysisXML.AnalyAddXMLNodeNew(list, clicknode.Tag.ToString(), clicknode.Text, Gvar.uo.m_displayName);
                                }
                            }
                        }
                        //操作数据库进行更新xml文档
                        RequestContent rc = new RequestContent() { systemName = ConfigHelper.AppSettings("getXml"), moudleName = "SYS_CaseCause\\ElementXML", fileType = "xml", fileName = clicknode.Tag.ToString(), content = txtXML.Text };
                        string weburl = ConfigHelper.AppSettings("xmlPath") + "/system/config/v1/setfilecontent";
                        ComResult model4 = WebUtil.DoPost<ComResult>(weburl, rc, "UTF-8");
                        if (model4.result.code == "1")
                        {
                            OperLogDAL.AddOperLog(Gvar.uo.m_displayName, "操作xml", rc.fileName + "-" + rc.moudleName, rc.content);
                            MessageBox.Show("添加成功，查看请刷新节点树!");
                        }
                        else if (model4.result.code == "0")
                        {
                            MessageBox.Show("添加失败！" + model4.result.message);
                        }
                        lblTS.Text = "";
                        this.Cursor = Cursors.Default;
                    });


                    #region MyRegion
                    //SYS_CaseCause caseCausexml1 = casecausebLL.GetCaseCauseByCCID(clicknode.Tag.ToString());
                    //caseCausexml1.ElementXML = Getxml("SYS_CaseCause\\ElementXML", caseCausexml1.CC_ID);
                    //if (string.IsNullOrEmpty(caseCausexml1.ElementXML))
                    //{
                    //    //判断逻辑 如果该案由下面有子节点则走新的添加节点的逻辑 否则节点数据走旧的添加节点的逻辑
                    //    DataTable dt = casecausebLL.Select_parentNode_child(clicknode.Tag.ToString());
                    //    if (dt == null || (dt.Rows.Count > 0 && dt.Select(" CC_Name= '" + strs + "'  ").Length == 0))
                    //    {
                    //        this.Cursor = Cursors.WaitCursor;
                    //        XmlNodeList list = document1.GetElementsByTagName(clicknode.Text);
                    //        if (list.Count > 0)
                    //        {
                    //            analysisXML.AnalyAddXMLNodeNew(list, clicknode.Tag.ToString(), clicknode.Text, Gvar.uo.m_displayName);
                    //            //操作数据库进行更新xml文档
                    //            RequestContent rc = new RequestContent() { systemName = ConfigHelper.AppSettings("getXml"), moudleName = "SYS_CaseCause\\ElementXML", fileType = "xml", fileName = clicknode.Tag.ToString(), content = txtXML.Text };
                    //            string weburl = ConfigHelper.AppSettings("xmlPath") + "/system/config/v1/setfilecontent";
                    //            ComResult model = WebUtil.DoPost<ComResult>(weburl, rc, "UTF-8");
                    //            if (model.result.code == "1")
                    //            {
                    //                OperLogDAL.AddOperLog(Gvar.uo.m_displayName, "操作xml", rc.fileName + "-" + rc.moudleName, rc.content);
                    //                MessageBox.Show("添加成功，查看请刷新节点树!");
                    //            }
                    //            else if (model.result.code == "0")
                    //            {
                    //                MessageBox.Show("添加失败！" + model.result.message);
                    //            }
                    //        }
                    //        this.Cursor = Cursors.Default;
                    //    }
                    //    else if (dt.Rows.Count == 0)
                    //    {
                    //        clicknode.Nodes.Clear();
                    //        this.Cursor = Cursors.WaitCursor;
                    //        XmlNodeList list = document1.GetElementsByTagName(clicknode.Text);
                    //        if (list.Count > 0)
                    //        {
                    //            analysisXML.AnalyAddXMLNode(list, clicknode.Tag.ToString(), clicknode.Text, Gvar.uo.m_displayName);
                    //            //操作数据库进行更新xml文档
                    //            RequestContent rc = new RequestContent() { systemName = ConfigHelper.AppSettings("getXml"), moudleName = "SYS_CaseCause\\ElementXML", fileType = "xml", fileName = clicknode.Tag.ToString(), content = txtXML.Text };
                    //            string weburl = ConfigHelper.AppSettings("xmlPath") + "/system/config/v1/setfilecontent";
                    //            ComResult model = WebUtil.DoPost<ComResult>(weburl, rc, "UTF-8");
                    //            if (model.result.code == "1")
                    //            {
                    //                OperLogDAL.AddOperLog(Gvar.uo.m_displayName, "操作xml", rc.fileName + "-" + rc.moudleName, rc.content);
                    //                MessageBox.Show("添加成功，查看请刷新节点树!");
                    //            }
                    //            else if (model.result.code == "0")
                    //            {
                    //                MessageBox.Show("添加失败！" + model.result.message);
                    //            }
                    //        }
                    //        this.Cursor = Cursors.Default;
                    //    }

                    //}
                    //else
                    //{
                    //    MsgBox.Err("该节点下已进行过事实要素xml模版配置，不能进行保存操作！");
                    //    return;
                    //} 
                    #endregion
                    #region MyRegion
                    //if (clicknode.Nodes.Count > 0 && casecausebLL.GetExpressSourceByCCId(clicknode.Tag.ToString()))
                    //{
                    //    MsgBox.Err("该节点下已配置来源规则，不能进行保存操作！");
                    //    return;
                    //}
                    //else
                    //{
                    //    clicknode.Nodes.Clear();
                    //    this.Cursor = Cursors.WaitCursor;
                    //    string XMLText = txtXML.Text.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @"");
                    //    XmlDocument document = new XmlDocument();
                    //    document.LoadXml(XMLText);
                    //    if (document.DocumentElement.Name == clicknode.Text)
                    //    {
                    //        XmlNodeList list = document.GetElementsByTagName(clicknode.Text);
                    //        if (list.Count > 0)
                    //        {
                    //            analysisXML.AnalyAddXMLNode(list, clicknode.Tag.ToString(), clicknode.Text, Gvar.uo.m_displayName);
                    //            //操作数据库进行更新xml文档
                    //            RequestContent rc = new RequestContent() { systemName = ConfigHelper.AppSettings("getXml"), moudleName = "SYS_CaseCause\\ElementXML", fileType = "xml", fileName = clicknode.Tag.ToString(), content = txtXML.Text };
                    //            string weburl = ConfigHelper.AppSettings("xmlPath") + "/system/config/v1/setfilecontent";
                    //            ComResult model = WebUtil.DoPost<ComResult>(weburl, rc, "UTF-8");
                    //            if (model.result.code == "1")
                    //            {
                    //                OperLogDAL.AddOperLog(Gvar.uo.m_displayName, "操作xml", rc.fileName + "-" + rc.moudleName, rc.content);
                    //                MessageBox.Show("添加成功，查看请刷新节点树!");
                    //            }
                    //            else if (model.result.code == "0")
                    //            {
                    //                MessageBox.Show("添加失败！" + model.result.message);
                    //            }
                    //            //bool res = casecausebLL.UpdateElementXML(clicknode.Tag.ToString(), txtXML.Text);
                    //            //if (res)
                    //            //{
                    //            //    this.Cursor = Cursors.Default;
                    //            //    MessageBox.Show("添加成功，查看请刷新节点树!");
                    //            //}
                    //        }

                    //    }
                    //    else
                    //    {
                    //        MsgBox.Err("添加失败！事实要素XML模板内容与" + clicknode.Text + "不匹配！");
                    //        return;
                    //    }
                    //} 
                    #endregion
                }
                else
                {
                    MsgBox.Err("事实要素xml模版内容为空！");
                    return;
                }
            }
            catch (Exception error)
            {
                MsgBox.Err("添加失败!" + error.Message);
                return;

            }
        }


        #endregion

        #region  字典属性 （第六个插页）
        public void ShowMatchKeyWord()
        {
            //有字典值的显示
            var matchValueCode = nodetree_argumenttypebll.IsExistMatchKeyWordCode(clicknode.Tag.ToString());
            var model = nodetree_argumenttypebll.GetMatchKeyWord(matchValueCode);
            if (model != null)
                txt_atchKeyWord.Text = model.AT_MatchKeyWord.Replace(";", ";\r\n").Replace("；", "；\r\n");
        }

        private void Save_MatchKeyWord_Click(object sender, EventArgs e)
        {
            try
            {
                var matchValueCode = nodetree_argumenttypebll.IsExistMatchKeyWordCode(clicknode.Tag.ToString());
                var model = nodetree_argumenttypebll.GetMatchKeyWord(matchValueCode);
                if (model != null)
                {
                    model.AT_MatchKeyWord = txt_atchKeyWord.Text;
                    nodetree_argumenttypebll.Update(model, model.AT_CauseID);
                    MessageBox.Show("保存成功！");
                }
            }
            catch (Exception error)
            {
                MessageBox.Show("保存失败！" + error);
            }

        }

        #endregion

        #region 事实要素优选XML模板(第七个插页)
        private void AddOptimizeXML_Click(object sender, EventArgs e)
        {
            if (casecausebLL.UpdateOptimizeXML(clicknode.Tag.ToString(), OptimizeXMLText.Text))
            { MessageBox.Show("保存成功!"); }
            else
            {
                MessageBox.Show("保存失败!");
            }
        }

        private void ShowOptimizeXML()
        {
            var dt = casecausebLL.GetSYS_CaseCauseByCCID(clicknode.Tag.ToString());
            OptimizeXMLText.Text = LdFormat.ObjectToString(dt.Rows[0]["OptimizeXML"]);
        }


        #endregion

        #region 要素属性XML (第八个插件)

        private void ShowArgumentTypeXml()
        {
            txt_ArgumentTypeXml.Text = string.Empty;
            //string webapiUrl1 = ConfigHelper.AppSettings("xmlPath") + "/system/config/v1/getfilecontent";
            //RequestContent rc = new RequestContent() { systemName = "Ldt_JudgeDocSystem", moudleName = "SYS_CaseCause\\ConfigXML", fileType = "xml", fileName = clicknode.Tag.ToString() };
            //ComResult model = WebUtil.DoPost<ComResult>(webapiUrl1, rc, "utf-8");
            //if (model.result.code == "1")
            //{
            //    txt_ArgumentTypeXml.Text = model.body.content;
            //}
            string xml = Getxml("SYS_CaseCause\\ConfigXML", clicknode.Tag.ToString());
            if (!string.IsNullOrEmpty(xml))
            {
                txt_ArgumentTypeXml.Text = xml;
            }
            //var dt = casecausebLL.GetSYS_CaseCauseByCCID(clicknode.Tag.ToString());
            //txt_ArgumentTypeXml.Text = LdFormat.ObjectToString(dt.Rows[0]["ConfigXML"]);
            MatchKeyWordText.Text = string.Empty;
            argumenttypeModel = null;
            dataPagerMain.ChangePageNumber(1);
        }

        private void btn_ArgumentTypeXml_Click(object sender, EventArgs e)
        {
            try
            {
                var Againlist = "";
                if (txt_ArgumentTypeXml.Text.Trim() != "")
                {
                    Againlist = analysisXML.AnalyArgumentTypeXml(txt_ArgumentTypeXml.Text);
                }

                if (Againlist.Contains("xmlPath"))
                { MessageBox.Show(Againlist); }
                else
                {
                    RequestContent rc = new RequestContent() { systemName = ConfigHelper.AppSettings("getXml"), moudleName = "SYS_CaseCause\\ConfigXML", fileType = "xml", fileName = clicknode.Tag.ToString(), content = txt_ArgumentTypeXml.Text };
                    string weburl = ConfigHelper.AppSettings("xmlPath") + "/system/config/v1/setfilecontent";
                    ComResult model = WebUtil.DoPost<ComResult>(weburl, rc, "UTF-8");
                    if (model.result.code == "1")
                    {
                        OperLogDAL.AddOperLog(Gvar.uo.m_displayName, "操作xml", rc.fileName + "-" + rc.moudleName, rc.content);
                        MessageBox.Show("添加成功，查看请刷新节点树!");
                    }
                    else if (model.result.code == "0")
                    {
                        MessageBox.Show("添加失败！" + model.result.message);
                    }

                    //casecausebLL.UpdateConfigXML(clicknode.Tag.ToString(), txt_ArgumentTypeXml.Text);
                }
            }
            catch (Exception error)
            {
                MessageBox.Show("添加失败!" + error);
            }
        }


        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SelectArgumentType_Click(object sender, EventArgs e)
        {
            dataPagerMain.ChangePageNumber(1);
            MatchKeyWordText.Text = "";
            argumenttypeModel = null;
            RowIndex = -1;

        }
        /// <summary>
        /// 回车查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SelectArguText_KeyPress(object sender, KeyPressEventArgs e)
        {

            dataPagerMain.ChangePageNumber(1);
            MatchKeyWordText.Text = "";
            argumenttypeModel = null;
            RowIndex = -1;

        }

        /// <summary>
        /// 显示字典列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void dataPagerMain_PageNumberChanging(object sender, Controls.DataPagerPageIndexChangingEventArgs e)
        {
            checkBox1.Checked = false;
            var startRowIndex = e.StartRowIndex;
            var maximumRows = e.MaximumRows;
            var endRowIndex = e.StartRowIndex + e.MaximumRows;
            var AT_CauseID = "";
            if (NotCauseID.Checked)
            {
                AT_CauseID = "";
            }
            else
            {
                AT_CauseID = clicknode.Tag.ToString();
            }
            var argumenttypedt = nodetree_argumenttypebll.GetList(AT_CauseID, SelectArguText.Text);
            if (argumenttypedt.Rows.Count > 0)
            {
                e.TotalCount = argumenttypedt.Rows.Count;
                var newdt = new DataTable();
                newdt = argumenttypedt.Clone();
                var dr = argumenttypedt.Select("ArgumentShowIndex>" + startRowIndex + " and ArgumentShowIndex<=" + endRowIndex);
                for (var i = 0; i < dr.Length; i++)
                {
                    newdt.ImportRow(dr[i]);
                }
                GV_ArgumentType.DataSource = newdt;


            }
            else
            {
                GV_ArgumentType.DataSource = new DataTable();
            }
        }

        /// <summary>
        /// 切换案由级
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ISCauseID_CheckedChanged(object sender, EventArgs e)
        {
            ShowArgumentType();
        }
        /// <summary>
        /// 切换“系统级”
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NotCauseID_CheckedChanged(object sender, EventArgs e)
        {
            ShowArgumentType();
        }

        /// <summary>
        /// 切换“案由级”
        /// </summary>
        public void ShowArgumentType()
        {
            SelectArguText.Text = "";
            dataPagerMain.ChangePageNumber(1);
            MatchKeyWordText.Text = "";
            argumenttypeModel = null;
            RowIndex = -1;

        }
        public string getAT_CauseID()
        {
            var AT_CauseID = "";
            if (NotCauseID.Checked)
            {
                AT_CauseID = "";
            }
            else
            {
                AT_CauseID = clicknode.Tag.ToString();
            }
            return AT_CauseID;
        }
        /// <summary>
        /// 点击显示字典值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GV_ArgumentType_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            argumenttypeModel = new SYS_ArgumentType();
            if (e.RowIndex != -1)
            {
                argumenttypeModel.AT_CauseID = getAT_CauseID();
                argumenttypeModel.AT_ID = GV_ArgumentType.Rows[e.RowIndex].Cells["AT_ID"].Value.ToString();
                argumenttypeModel.AT_Code = GV_ArgumentType.Rows[e.RowIndex].Cells["AT_Code"].Value.ToString();
                argumenttypeModel.AT_Name = GV_ArgumentType.Rows[e.RowIndex].Cells["AT_Name"].Value.ToString();
                argumenttypeModel.AT_MatchKeyWord = GV_ArgumentType.Rows[e.RowIndex].Cells["AT_MatchKeyWord"].Value.ToString();
                MatchKeyWordText.Text = argumenttypeModel.AT_MatchKeyWord.Replace("\r", "").Replace(";", ";\n").Replace("；", "；\n");
                RowIndex = e.RowIndex;
            }
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ArgumentAdd_Click(object sender, EventArgs e)
        {
            var nodetree_addargumenttype = new NodeTree_AddArgumentType();
            nodetree_addargumenttype.AT_ID = "";
            nodetree_addargumenttype.AT_CauseID = getAT_CauseID();
            nodetree_addargumenttype.AT_Code = "";
            nodetree_addargumenttype.AT_Name = "";
            nodetree_addargumenttype.AT_MatchKeyWord = "";
            nodetree_addargumenttype.CC_ID = clicknode.Tag.ToString();
            nodetree_addargumenttype.ShowDialog();
            SelectArgumentType_Click(null, null);
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ArgumentUpdate_Click(object sender, EventArgs e)
        {
            int j = 0;
            for (var i = 0; i <= GV_ArgumentType.Rows.Count - 1; i++)
            {
                var check = (DataGridViewCheckBoxCell)GV_ArgumentType.Rows[i].Cells["Select"];
                if (Convert.ToBoolean(check.Value))
                {
                    j++;
                }
            }
            if (j < 1)
            {
                MessageBox.Show("请选择需要修改的数据后再试！");
                return;
            }
            else if (j == 1)
            {
                var nodetree_addargumenttype = new NodeTree_AddArgumentType();
                nodetree_addargumenttype.AT_CauseID = getAT_CauseID();
                for (var i = 0; i <= GV_ArgumentType.Rows.Count - 1; i++)
                {
                    var check = (DataGridViewCheckBoxCell)GV_ArgumentType.Rows[i].Cells["Select"];
                    if (Convert.ToBoolean(check.Value))
                    {
                        nodetree_addargumenttype.AT_ID = GV_ArgumentType.Rows[i].Cells["AT_ID"].Value.ToString();
                        nodetree_addargumenttype.AT_Code = GV_ArgumentType.Rows[i].Cells["AT_Code"].Value.ToString();
                        nodetree_addargumenttype.AT_Name = GV_ArgumentType.Rows[i].Cells["AT_Name"].Value.ToString();
                        nodetree_addargumenttype.AT_MatchKeyWord = GV_ArgumentType.Rows[i].Cells["AT_MatchKeyWord"].Value.ToString();
                        nodetree_addargumenttype.CC_ID = clicknode.Tag.ToString();
                        break;
                    }
                }
                nodetree_addargumenttype.Show();

            }
            else if (j > 1)
            {
                MessageBox.Show("请选择需要修改的一条数据后再试！");
                return;
            }
        }
        /// <summary>
        /// 只保存文本
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveMatchKeyWord_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(MatchKeyWordText.Text))
                {
                    MessageBox.Show("请添加需要修改的要素属性文本内容！");
                    return;
                }
                else if (argumenttypeModel != null)
                {
                    argumenttypeModel.AT_MatchKeyWord = MatchKeyWordText.Text;
                    nodetree_argumenttypebll.Update(argumenttypeModel, clicknode.Tag.ToString());
                    GV_ArgumentType.Rows[RowIndex].Cells["AT_MatchKeyWord"].Value = MatchKeyWordText.Text.Replace("\n", "");
                    MessageBox.Show("修改文本成功！");
                }
                else if (argumenttypeModel == null)
                {
                    MsgBox.Warn("请选择字典值后再试！");
                }
            }
            catch (Exception error)
            {
                MessageBox.Show("修改文本失败！" + error);
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ArgumentDelete_Click(object sender, EventArgs e)
        {
            int j = 0;
            for (var i = 0; i <= GV_ArgumentType.Rows.Count - 1; i++)
            {
                var check = (DataGridViewCheckBoxCell)GV_ArgumentType.Rows[i].Cells["Select"];
                if (Convert.ToBoolean(check.Value))
                {
                    j++;
                }
            }
            if (j < 1)
            {
                MessageBox.Show("请选择需要删除的数据后再试！");
                return;
            }
            var DeleteID = "";
            if (MessageBox.Show("确认要删除数据吗？", "此删除不可恢复", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    for (var i = 0; i <= GV_ArgumentType.Rows.Count - 1; i++)
                    {
                        var check = (DataGridViewCheckBoxCell)GV_ArgumentType.Rows[i].Cells["Select"];
                        if (Convert.ToBoolean(check.Value))
                        {
                            DeleteID = GV_ArgumentType.Rows[i].Cells["AT_ID"].Value.ToString();
                            if (DeleteID != "")
                            {
                                nodetree_argumenttypebll.Delete(DeleteID);
                                MessageBox.Show("删除成功!");
                            }
                        }
                    }
                }
                catch //(Exception error)
                {
                    MessageBox.Show("删除失败!");
                }
                ShowArgumentType();
            }
        }

        /// <summary>
        /// 全选、反选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            var flag = true;
            if (checkBox1.Checked)
                flag = true;
            else flag = false;
            for (var i = 0; i <= GV_ArgumentType.Rows.Count - 1; i++)
            {
                var check = (DataGridViewCheckBoxCell)GV_ArgumentType.Rows[i].Cells["Select"];
                check.Value = flag;
            }
        }


        #endregion

        #region 基本属性 (第九个插件)

        private void ShowBaseProperty()
        {
            //父级名称显示
            if (clicknode.Level == 0)
            {
                txbParentName.Text = "";
            }
            else
            {
                txbParentName.Text = clicknode.Parent.Text;
            }

            var dt = casecausebLL.GetSYS_CaseCauseByCCID(clicknode.Tag.ToString());
            //CC_ID
            CC_ID2.Text = clicknode.Tag.ToString();
            //节点名称
            Childname2.Text = dt.Rows[0]["CC_Name"].ToString();

            //显示名称
            txbShowName.Text = dt.Rows[0]["PIS_ShowName"].ToString();

            //显示地域
            cmbSysDistrict.Text = new Xzzf_DisWfRelBLL().GetSystrictByDisWfRel(clicknode.Tag.ToString());

            if (!string.IsNullOrEmpty(cmbSysDistrict.Text))
            {
                List<string> sysDistricts = cmbSysDistrict.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                if (sysDistricts.Count > 0 && cmbSysDistrict.TreeView.Nodes.Count > 0)
                {
                    for (int i = 0; i < cmbSysDistrict.TreeView.Nodes.Count; i++)
                    {
                        if (sysDistricts.Any(x => x.Equals(cmbSysDistrict.TreeView.Nodes[i].Text)))
                        {
                            cmbSysDistrict.TreeView.Nodes[i].Checked = true;
                        }
                    }
                }
            }

            //是否机器学习
            cmbIsML.Text = string.IsNullOrEmpty(dt.Rows[0]["IsML"].ToString()) ? "" : Convert.ToInt32(dt.Rows[0]["IsML"].ToString()) == 0 ? "否" : "是";

            //是否显示组合表述
            if (!string.IsNullOrEmpty(dt.Rows[0]["CC_IsCombination"].ToString()) && Convert.ToInt32(dt.Rows[0]["CC_IsCombination"].ToString()) == 1)
            {
                CC_IsCombination_Y2.Checked = true;
            }
            else
            {
                CC_IsCombination_N2.Checked = true;
            }
            //是否匹配表述根节点
            if (!string.IsNullOrEmpty(dt.Rows[0]["CC_IsProcessNode"].ToString()) && Convert.ToInt32(dt.Rows[0]["CC_IsProcessNode"].ToString()) == 1)
            {
                CC_IsProcessNode_Y2.Checked = true;
            }
            else
            {
                CC_IsProcessNode_N2.Checked = true;
            }
            //是否表述要素
            if (dt.Rows[0]["CC_ExpressElement"].ToString() != "" && Convert.ToInt32(dt.Rows[0]["CC_ExpressElement"].ToString()) == 1)
            {
                ExpressElement_Y2.Checked = true;
            }
            else if (dt.Rows[0]["CC_ExpressElement"].ToString() == "" || Convert.ToInt32(dt.Rows[0]["CC_ExpressElement"].ToString()) == 0)
            {
                ExpressElement_N2.Checked = true;
            }
            //是否为核心要素
            if (dt.Rows[0]["CC_IsBasicElements"].ToString() != "" && Convert.ToInt32(dt.Rows[0]["CC_IsBasicElements"].ToString()) == 1)
            {
                radioBtnBaseElementYes.Checked = true;
            }
            else if (dt.Rows[0]["CC_IsBasicElements"].ToString() == "" || Convert.ToInt32(dt.Rows[0]["CC_IsBasicElements"].ToString()) == 0)
            {
                radioBtnBaseElementNo.Checked = true;
            }
            //加载类别
            Typedt = casecausebLL.GetCaseCauseType();
            NodeTypeList2.DataSource = Typedt;
            NodeTypeList2.DisplayMember = "CC_NodeTypeName";
            NodeTypeList2.ValueMember = "CC_NodeType";
            NodeTypeList2.SelectedValue = dt.Rows[0]["CC_NodeType"].ToString();

            if (clicknode.Text != "属性" && (NodeTypeList2.Text == "XML节点" || NodeTypeList2.Text == "XML属性"))
            {
                DataTable caseCauseTable = casecausebLL.GetCaseCauseTypeByNodeType();
                if (caseCauseTable != null && caseCauseTable.Rows.Count > 0)
                {
                    label37.Visible = true;
                    cbNodeType2.Visible = true;
                    DataRow dr = caseCauseTable.NewRow();
                    cbNodeType2.DataSource = caseCauseTable;
                    cbNodeType2.DisplayMember = "CC_NodeTypeName";
                    cbNodeType2.ValueMember = "CC_NodeType";
                    cbNodeType2.SelectedValue = string.IsNullOrEmpty(dt.Rows[0]["CC_NodeSubType"].ToString()) ? 0 : Convert.ToInt32(dt.Rows[0]["CC_NodeSubType"].ToString());
                    //事实要素显示是否核心要素
                    if (Convert.ToInt32(cbNodeType2.SelectedValue) == 19)
                    {
                        panelBaseElements.Visible = true;
                    }
                    else
                    {
                        panelBaseElements.Visible = false;
                    }
                }
            }
            else
            {
                label37.Visible = false;
                cbNodeType2.Visible = false;
                panelBaseElements.Visible = false;
            }
            //法定情节 Name=5，酌定情节 Name=6
            if ((clicknode.Name == "5") && clicknode.FullPath.Contains("刑事罪名"))
            {
                DataTable dtXFAdjustment = xfPunishimentAdjustmentBll.GetAdjustment(clicknode.Tag.ToString());
                panelFDX.Visible = true;
                DataTable dtt = new DataTable();
                dtt.Columns.Add("Id");
                dtt.Columns.Add("Name");
                SYS_ArgumentType sat = nodetree_argumenttypebll.GetMatchKeyWord("SentenceID");
                if (!string.IsNullOrEmpty(sat.AT_MatchKeyWord))
                {
                    string[] strs = sat.AT_MatchKeyWord.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string str in strs)
                    {
                        string[] str1 = str.Split('=');
                        if (str1.Length > 0)
                        {
                            DataRow dr = dtt.NewRow();
                            dr["Id"] = str1[0].ToString();
                            dr["Name"] = str1[1].ToString();
                            dtt.Rows.Add(dr);
                        }
                    }
                    if (dtt.Rows.Count > 0)
                    {
                        DataRow dr = dtt.NewRow();
                        dr["Id"] = "0";
                        dr["Name"] = ""; ;
                        dtt.Rows.InsertAt(dr, 0);
                        cbxSentence.DataSource = dtt;
                        cbxSentence.DisplayMember = "Name";
                        cbxSentence.ValueMember = "Id";
                        if (dtXFAdjustment != null && dtXFAdjustment.Rows.Count > 0 && !string.IsNullOrEmpty(dtXFAdjustment.Rows[0]["PA_SentenceID"].ToString()))
                        {
                            cbxSentence.SelectedValue = dtXFAdjustment.Rows[0]["PA_SentenceID"].ToString();
                        }
                    }
                }
                DataTable dttAdj = new DataTable();
                dttAdj.Columns.Add("Id");
                dttAdj.Columns.Add("Name");
                SYS_ArgumentType satAdj = nodetree_argumenttypebll.GetMatchKeyWord("AdjustTypeID");
                if (!string.IsNullOrEmpty(satAdj.AT_MatchKeyWord))
                {
                    string[] strs = satAdj.AT_MatchKeyWord.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string str in strs)
                    {
                        string[] str1 = str.Split('=');
                        if (str1.Length > 0)
                        {
                            DataRow dr = dttAdj.NewRow();
                            dr["Id"] = str1[0].ToString();
                            dr["Name"] = str1[1].ToString();
                            dttAdj.Rows.Add(dr);
                        }
                    }
                    if (dttAdj.Rows.Count > 0)
                    {
                        DataRow dr = dttAdj.NewRow();
                        dr["Id"] = "0";
                        dr["Name"] = ""; ;
                        dttAdj.Rows.InsertAt(dr, 0);
                        cbxAdjustType.DataSource = dttAdj;
                        cbxAdjustType.DisplayMember = "Name";
                        cbxAdjustType.ValueMember = "Id";
                        if (dtXFAdjustment != null && dtXFAdjustment.Rows.Count > 0 && !string.IsNullOrEmpty(dtXFAdjustment.Rows[0]["PA_AdjustTypeID"].ToString()))
                        {
                            cbxAdjustType.SelectedValue = dtXFAdjustment.Rows[0]["PA_AdjustTypeID"].ToString();
                        }
                    }
                }
            }
            else
            {
                panelFDX.Visible = false;
            }
            if (((clicknode.Name == "5" || clicknode.Name == "6") && clicknode.FullPath.Contains("刑事罪名")) || (clicknode.Name == "30" || clicknode.Name == "33" || clicknode.Name == "34"))
            {
                label40.Visible = comboBox2.Visible = true;
                DataTable dtt = new DataTable();
                dtt.Columns.Add("Id");
                dtt.Columns.Add("Name");
                SYS_ArgumentType sat = nodetree_argumenttypebll.GetMatchKeyWord("MC_influenceTypeID");
                if (!string.IsNullOrEmpty(sat.AT_MatchKeyWord))
                {
                    string[] strs = sat.AT_MatchKeyWord.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string str in strs)
                    {
                        string[] str1 = str.Split('=');
                        if (str1.Length > 0)
                        {
                            DataRow dr = dtt.NewRow();
                            dr["Id"] = str1[0].ToString();
                            dr["Name"] = str1[1].ToString();
                            dtt.Rows.Add(dr);
                        }
                    }
                    if (dtt.Rows.Count > 0)
                    {
                        DataRow dr = dtt.NewRow();
                        dr["Id"] = "0";
                        dr["Name"] = ""; ;
                        dtt.Rows.InsertAt(dr, 0);
                        comboBox2.DataSource = dtt;
                        comboBox2.DisplayMember = "Name";
                        comboBox2.ValueMember = "Id";
                        if (!string.IsNullOrEmpty(dt.Rows[0]["MC_influenceTypeID"].ToString()))
                        {
                            comboBox2.SelectedValue = dt.Rows[0]["MC_influenceTypeID"].ToString();
                        }
                    }
                }
            }
            else
            {
                label40.Visible = comboBox2.Visible = false;
            }
            ArgumentTypeXmlBLL bll = new ArgumentTypeXmlBLL();
            var dlsdt = bll.GetArgumentDtByType("DevelopSchedule");
            DevelopSchedule.DataSource = dlsdt;
            DevelopSchedule.DisplayMember = "AM_Name";
            DevelopSchedule.ValueMember = "AM_Code";
            DevelopSchedule.SelectedValue = dt.Rows[0]["CC_DevelopSchedule"].ToString();
            var ccdt = bll.GetArgumentDtByType("CommonCase");
            CommonCase.DataSource = ccdt;
            CommonCase.DisplayMember = "AM_Name";
            CommonCase.ValueMember = "AM_Code";
            CommonCase.SelectedValue = dt.Rows[0]["CC_CommonCase"].ToString();
            // NodeTypeList2_SelectedIndexChanged(null, null);
            if (NodeTypeList2.Text.Equals("案由") || NodeTypeList2.Text.Equals("拆分罪名"))
            {
                if (Gvar.uo.m_deptId.Equals("E5B95A61-A3E5-424C-B01A-D1D5901A4B52"))
                {
                    Childname2.ReadOnly = txbShowName.ReadOnly = false;
                }
                else
                {
                    Childname2.ReadOnly = txbShowName.ReadOnly = true;
                }
            }
            else
            {
                Childname2.ReadOnly = txbShowName.ReadOnly = false;
            }
        }

        private void NodeTypeList2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (NodeTypeList2.SelectedValue != null && NodeTypeList2.SelectedValue.ToString() == "2")
            {
                label35.Visible = true;
                DevelopSchedule.Visible = true;
            }
            else
            {
                label35.Visible = false;
                DevelopSchedule.Visible = false;
            }
            if (NodeTypeList2.Text == "XML节点" || NodeTypeList2.Text == "XML属性" && clicknode.Text != "属性")
            {
                DataTable caseCauseTable = casecausebLL.GetCaseCauseTypeByNodeType();
                if (caseCauseTable != null && caseCauseTable.Rows.Count > 0)
                {
                    label37.Visible = true;
                    cbNodeType2.Visible = true;
                    cbNodeType2.DataSource = caseCauseTable;
                    cbNodeType2.DisplayMember = "CC_NodeTypeName";
                    cbNodeType2.ValueMember = "CC_NodeType";
                    //  cbNodeType2.SelectedValue = -1;
                }
            }
            else
            {
                label37.Visible = false;
                cbNodeType2.Visible = false;
                cbNodeType2.SelectedValue = 0;
                //btnDefaultSource.Visible = false;
            }
            if (NodeTypeList2.Text.Equals("案由") || NodeTypeList2.Text.Equals("拆分罪名"))
            {
                if (Gvar.uo.m_deptId.Equals("E5B95A61-A3E5-424C-B01A-D1D5901A4B52"))
                {
                    Childname2.ReadOnly = txbShowName.ReadOnly = false;
                }
                else
                {
                    Childname2.ReadOnly = txbShowName.ReadOnly = true;
                }
            }
            else
            {
                Childname2.ReadOnly = txbShowName.ReadOnly = false;
            }
        }

        /// <summary>
        /// 节点属性页面保存节点信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveBaseProperty_Click(object sender, EventArgs e)
        {
            //民事案由需要判断是否有权限
            if (clicknode.FullPath.Substring(0, 4) == "民事案由")
            {
                if (users.Contains(Gvar.uo.m_displayName))
                {
                    SaveNode();
                }
                else
                {
                    MessageBox.Show("该用户没有操作民事案由的权限");
                    return;
                }
            }//行政执法判断是否有权限
            else if (clicknode.FullPath.Substring(0, 4) == "行政执法")
            {
                if (userXZs.Contains(Gvar.uo.m_displayName))
                {
                    SaveNode();
                }
                else
                {
                    MessageBox.Show("该用户没有操作行政执法的权限");
                    return;
                }
            }
            else
            {
                SaveNode();
            }
        }

        /// <summary>
        /// 修改保存节点
        /// </summary>
        private void SaveNode()
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                string oldName = clicknode.Text;
                int type = Convert.ToInt32(NodeTypeList2.SelectedValue);

                if (string.IsNullOrEmpty(Childname2.Text))
                {
                    MsgBox.Warn("名称不能为空！");
                    Childname2.Focus();
                    return;
                }
                if (oldName != "属性" && clicknode.Nodes.Count > 0 && type == 12)
                {
                    MsgBox.Warn("名称非“属性”节点，有下级类型时不能改为XML属性!");
                    return;
                }
                if (clicknode.Parent != null && clicknode.Parent.Text == "属性" && type == 11)
                {
                    MsgBox.Warn("“属性”的下级属性节点不能直接改为xml节点！");
                    return;
                }
                //当前节点Model
                var model = casecausebLL.GetCaseCauseByCCID(clicknode.Tag.ToString());
                SYS_CaseCause nowNode1 = null;
                if (clicknode.Parent != null)
                {
                    //父级节点Model
                    nowNode1 = casecausebLL.GetCaseCauseByCCID(clicknode.Parent.Tag.ToString());
                }
                //父级的第一个案由节点
                SYS_CaseCause caseCausexml = casecausebLL.IsParentRealation1(model.CC_ID);
                caseCausexml.ElementXML = Getxml("SYS_CaseCause\\ElementXML", caseCausexml.CC_ID);
                //如果节点名称已经改变
                if (oldName != Childname2.Text.Trim())
                {
                    //民事案由涉及到xml维护，xml中名字不能以数字开头或者数字
                    if (clicknode.FullPath.StartsWith("民事案由"))
                    {
                        int tmp;
                        if (int.TryParse(Childname2.Text, out tmp) || char.IsDigit(Childname2.Text[0]))
                        {
                            MsgBox.Warn("名称不能以数字开头或数字！");
                            return;
                        }
                    }
                    //类型为xml节点或者xml属性则节点名称不能包含非数字字母
                    if (type == 12 || type == 11)
                    {
                        bool res = Childname2.Text.Any(x =>
                              {
                                  return !char.IsLetter(x) && !char.IsNumber(x);
                              });
                        if (res)
                        {
                            MsgBox.Warn("包含特殊字符的节点不能改为XML节点和XML属性！");
                            return;
                        }
                        //foreach (char c in Childname2.Text)
                        //{
                        //    if (!char.IsLetter(c) && !char.IsNumber(c))
                        //    {
                        //        MsgBox.Warn("包含特殊字符的节点不能改为XML节点和XML属性！");
                        //        return;
                        //    }
                        //}

                        #region 进行判断xml配置中是否已经存在xml节点或者xml属性，如果已经存在就不能修改类型                        

                        if (!string.IsNullOrEmpty(caseCausexml.ElementXML))
                        {
                            XmlDocument doc = new XmlDocument();
                            XmlNode objxml;
                            string xml = caseCausexml.ElementXML.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @"");
                            doc.LoadXml(xml);
                            string res4 = GetXmlPath(model.AllParentName, caseCausexml.CC_Name, model.CC_Name);

                            if (!string.IsNullOrEmpty(res4))
                            {
                                objxml = doc.SelectSingleNode(res4);
                                if (type == 11)
                                {
                                    if (objxml != null && model.CC_NodeType != 11)
                                    {
                                        MsgBox.Warn("XML中已存在该节点，不能修改类型！");
                                        NodeTypeList2.SelectedValue = model.CC_NodeType;
                                        cbNodeType2.SelectedValue = model.CC_NodeSubType;
                                        return;
                                    }
                                }
                                if (type == 12)
                                {
                                    if (objxml != null && model.CC_NodeType != 12)
                                    {
                                        XmlElement ob = (XmlElement)objxml;
                                        if (ob.HasAttribute(model.CC_Name))
                                        {
                                            MsgBox.Warn("XML中已存在该属性节点，不能修改类型！");
                                            NodeTypeList2.SelectedValue = model.CC_NodeType;
                                            cbNodeType2.SelectedValue = model.CC_NodeSubType;
                                            return;
                                        }
                                    }
                                }
                            }
                        }
                        #endregion
                    }

                }


                //如果是由其他类型改为XML属性
                if (model.CC_NodeType != 12 && type == 12)
                {
                    try
                    {
                        //获取属性节点     
                        if (clicknode.Parent.Text != "属性")
                        {
                            string objProperty = casecausebLL.IsHaveProperty(clicknode.Parent.Tag.ToString());
                            if (string.IsNullOrEmpty(objProperty))
                            {
                                var model1 = new SYS_CaseCause();

                                //创建属性节点
                                model1.CC_ID = newid.JudgeDoc_CreateID("SYS_CaseCause");
                                model1.CC_Name = "属性";
                                model1.CC_ParentID = clicknode.Parent.Tag.ToString();
                                model1.CC_NodeType = 12;
                                model1.AllParentId = nowNode1.AllParentId + "," + model1.CC_ID;
                                model1.AllParentName = nowNode1.AllParentName + "," + model1.CC_Name;
                                model1.HW_level = model1.AllParentName.Split(',').Length;
                                model1.CC_SerialNumb = 1;
                                casecausebLL.AddPropertyUpdateSerialNum(model1.CC_ParentID);
                                model1.XmlPath = nowNode1.XmlPath;
                                if (casecausebLL.AddSYS_CaseCause(model1, Gvar.uo.m_displayName))
                                {
                                    //添加成功属性节点
                                    // casecausebLL.UpdateXmlPath(model.CC_ID);
                                    // casecausebLL.CaseCauseUpdateAllPid(model.CC_ID);
                                    var addnode = new TreeNode();
                                    addnode.Tag = model1.CC_ID;
                                    addnode.Text = model1.CC_Name;
                                    addnode.Name = model1.CC_NodeType.ToString();
                                    editnode.Parent.Nodes.Insert(0, addnode);
                                    editnode.Expand();
                                    nowNode1 = model1;
                                }
                            }
                            else
                            {
                                nowNode1 = casecausebLL.GetCaseCauseByCCID(objProperty);
                            }
                        }

                        //赋值来源节点的内容                     
                        model.CC_ParentID = nowNode1.CC_ID.ToString();
                        model.CC_NodeType = type;
                        model.CC_NodeSubType = cbNodeType2.Visible == true ? Convert.ToInt32(cbNodeType2.SelectedValue) : 0;
                        model.AllParentId = nowNode1.AllParentId + "," + model.CC_ID;
                        model.AllParentName = nowNode1.AllParentName + "," + model.CC_Name;
                        model.CC_SerialNumb = casecausebLL.GetNodeChildSerialNumber(nowNode1.CC_ID.ToString());
                        model.HW_level = model.AllParentName.Split(',').Length;
                        model.IsML = string.IsNullOrEmpty(cmbIsML.Text.Trim()) ? 0 : cmbIsML.Text.Trim() == "是" ? 1 : 0;
                        //model.CC_District = GetDistrcts(cmbSysDistrict.checkNodeList);
                        if (panelBaseElements.Visible == true)
                        {
                            model.CC_IsBasicElements = radioBtnBaseElementYes.Checked ? 1 : 0;
                        }
                        model.XmlPath = GetXmlPath(model.AllParentName, caseCausexml.CC_Name, model.CC_Name);
                        if (casecausebLL.UpdateSYS_CaseCause(model, Gvar.uo.m_displayName))
                        {
                            var addnode = new TreeNode();
                            addnode.Tag = model.CC_ID;
                            addnode.Text = model.CC_Name;
                            addnode.Name = "12";

                            TreeNode attbuteNode = null;
                            if (clicknode.Parent.Text != "属性")
                            {
                                foreach (TreeNode r in clicknode.Parent.Nodes)
                                {
                                    if (r.Text == "属性")
                                    {
                                        attbuteNode = r;
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                attbuteNode = clicknode.Parent;
                            }
                            attbuteNode.Nodes.Insert(0, addnode);
                            attbuteNode.Expand();
                            clicknode.Parent.Nodes.Remove(clicknode);

                            if (type == 12 || type == 11)
                            {
                                if (!string.IsNullOrEmpty(caseCausexml.ElementXML))
                                {
                                    XmlDocument doc = new XmlDocument();
                                    XmlNode objxml;
                                    XmlNode objxml1;
                                    string xml = caseCausexml.ElementXML.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @"");
                                    doc.LoadXml(xml);
                                    string res2 = string.Empty;
                                    string res3 = string.Empty;
                                    if (model.AllParentName.Contains(",属性"))
                                    {
                                        int res01 = model.AllParentName.LastIndexOf(",属性");
                                        res2 = model.AllParentName.Substring(0, res01);
                                    }
                                    res3 = model.AllParentName.Replace(",属性", "");
                                    //int j = res3.LastIndexOf(caseCausexml.CC_Name);
                                    int j = 0;
                                    string ayysId = casecausebLL.GetAyysIDByName(caseCausexml.CC_ID);
                                    if (!string.IsNullOrEmpty(ayysId) && res3.Contains("案由要素"))
                                    {
                                        j = res3.LastIndexOf("案由要素");
                                    }
                                    else
                                    {
                                        j = res3.LastIndexOf(caseCausexml.CC_Name);
                                    }
                                    string xmlPath1 = res3.Substring(j);
                                    string[] strs1 = xmlPath1.Split(',');
                                    StringBuilder sb1 = new StringBuilder();
                                    foreach (var item in strs1)
                                    {
                                        sb1.Append("/" + item);
                                    }
                                    //原节点路由
                                    string res4 = sb1.ToString();

                                    //int i = res2.LastIndexOf(caseCausexml.CC_Name);
                                    int i = 0;
                                    if (!string.IsNullOrEmpty(ayysId) && res2.Contains("案由要素"))
                                    {
                                        i = res2.LastIndexOf("案由要素");
                                    }
                                    else
                                    {
                                        i = res2.LastIndexOf(caseCausexml.CC_Name);
                                    }
                                    string xmlPath = res2.Substring(i);
                                    string[] strs = xmlPath.Split(',');
                                    StringBuilder sb = new StringBuilder();
                                    foreach (var item in strs)
                                    {
                                        sb.Append("/" + item);
                                    }
                                    //原节点路由
                                    string res1 = sb.ToString();
                                    if (!string.IsNullOrEmpty(res1) && !string.IsNullOrEmpty(res4))
                                    {
                                        objxml = doc.SelectSingleNode(res1);
                                        objxml1 = doc.SelectSingleNode(res4);
                                        if (objxml != null)
                                        {
                                            if (objxml1 != null)
                                            {
                                                objxml.RemoveChild(objxml1);
                                            }
                                            XmlElement objxml001 = (XmlElement)objxml;
                                            objxml001.SetAttribute(model.CC_Name, "");
                                        }
                                    }
                                    if (!string.IsNullOrEmpty(doc.InnerXml.ToString()))
                                    {
                                        string res5 = FormatXML(doc.InnerXml.ToString());
                                        bool res = casecausebLL.UpdateElementXML(caseCausexml.CC_ID, res5);
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("修改为xml属性出错:" + ex.Message);
                        return;
                    }
                }
                else
                {
                    try
                    {
                        model.CC_Name = Childname2.Text.Replace("\r\n", "").Trim();
                        model.CC_NodeType = Convert.ToInt32(NodeTypeList2.SelectedValue);
                        model.PIS_ShowName = txbShowName.Text.Trim();
                        model.CC_IsProcessNode = CC_IsProcessNode_N2.Checked ? 0 : 1;
                        model.CC_IsCombination = CC_IsCombination_N2.Checked ? 0 : 1;
                        model.CC_ExpressElement = ExpressElement_N2.Checked ? 0 : 1;
                        model.CC_CommonCase = Convert.ToInt32(CommonCase.SelectedValue);
                        model.CC_DevelopSchedule = Convert.ToInt32(DevelopSchedule.SelectedValue);
                        model.CC_NodeSubType = cbNodeType2.Visible == true ? Convert.ToInt32(cbNodeType2.SelectedValue) : 0;
                        //顶级节点的allparentname为他本身
                        model.AllParentName = nowNode1 != null ? nowNode1.AllParentName + "," + model.CC_Name : model.CC_Name;
                        model.IsML = string.IsNullOrEmpty(cmbIsML.Text.Trim()) ? 0 : cmbIsML.Text.Trim() == "是" ? 1 : 0;
                        //model.CC_District = GetDistrcts(cmbSysDistrict.checkNodeList);
                        //核心要素
                        if (panelBaseElements.Visible == true)
                        {
                            model.CC_IsBasicElements = radioBtnBaseElementYes.Checked ? 1 : 0;
                        }
                        //量刑结果类型
                        if (comboBox2.Visible == true && !string.IsNullOrEmpty(comboBox2.Text.Trim()))
                        {
                            model.MC_influenceTypeID = comboBox2.SelectedValue.ToString();
                        }
                        model.XmlPath = GetXmlPath(model.AllParentName, caseCausexml.CC_Name, model.CC_Name);
                        if (casecausebLL.UpdateSYS_CaseCause(model, Gvar.uo.m_displayName))
                        {
                            casecausebLL.CaseCauseUpdateAllPid(model.CC_ID);
                            //修改父级及所有子级的地域属性
                            //if (!string.IsNullOrWhiteSpace(model.CC_District))
                            //    casecausebLL.UpdateSysDistrict(model.CC_ID, model.CC_District);
                            //casecausebLL.UpdateXmlPath(model.CC_ID);
                            //MessageBox.Show("节点编辑成功！");
                            clicknode.Text = model.CC_Name;
                            clicknode.Name = model.CC_NodeType.ToString();
                            if (model.CC_CommonCase == 1 && ISCommonCase == 1)
                                clicknode.ForeColor = Color.Blue;
                            else clicknode.ForeColor = Color.Black;
                            //tVCaseCause.SelectedNode = null;


                            SYS_CaseCause nowNode = casecausebLL.GetCaseCauseByCCID(model.CC_ID);
                            if (type == 12 || type == 11)
                            {
                                if (!string.IsNullOrEmpty(caseCausexml.ElementXML))
                                {
                                    XmlDocument doc = new XmlDocument();
                                    string xml = caseCausexml.ElementXML.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @"");
                                    doc.LoadXml(xml);
                                    if (type == 12 && model.CC_NodeType != 12)
                                    {
                                        string res21 = string.Empty;
                                        //string res31 = string.Empty;
                                        if (model.AllParentName.Contains(",属性"))
                                        {
                                            int res01 = model.AllParentName.LastIndexOf(",属性");
                                            res21 = model.AllParentName.Substring(0, res01);
                                        }
                                        int j = 0;
                                        string ayysId = casecausebLL.GetAyysIDByName(caseCausexml.CC_ID);
                                        if (!string.IsNullOrEmpty(ayysId) && res21.Contains("案由要素"))
                                        {
                                            j = res21.LastIndexOf("案由要素");
                                        }
                                        else
                                        {
                                            j = res21.LastIndexOf(caseCausexml.CC_Name);
                                        }
                                        string xmlPath1 = res21.Substring(j);
                                        string[] strs1 = xmlPath1.Split(',');
                                        StringBuilder sb1 = new StringBuilder();
                                        foreach (var item in strs1)
                                        {
                                            sb1.Append("/" + item);
                                        }
                                        //原节点路由
                                        string res4 = sb1.ToString();
                                        XmlNode objxml1 = doc.SelectSingleNode(res4);
                                        if (objxml1 != null)
                                        {
                                            XmlElement objxml001 = (XmlElement)objxml1;
                                            objxml001.RemoveAttribute(oldName);
                                        }
                                        if (!string.IsNullOrEmpty(doc.InnerXml.ToString()))
                                        {
                                            bool res = casecausebLL.UpdateElementXML(caseCausexml.CC_ID, FormatXML(doc.InnerXml.ToString()));
                                            if (res)
                                            {
                                                // MsgBox.OK("添加成功，查看请刷新节点树!");
                                            }
                                            else
                                            {
                                                MsgBox.Err("更新xml结构失败！");
                                            }
                                        }
                                    }
                                    else
                                    {
                                        string xmlPath1 = string.Empty;
                                        string xmlPa = string.Empty;
                                        if (model.AllParentName.Contains(",属性"))
                                        {
                                            int res01 = model.AllParentName.LastIndexOf(",属性");
                                            xmlPath1 = model.AllParentName.Substring(0, res01);
                                            //int j = xmlPath1.LastIndexOf(caseCausexml.CC_Name);

                                            int j = 0;
                                            string ayysId = casecausebLL.GetAyysIDByName(caseCausexml.CC_ID);
                                            if (!string.IsNullOrEmpty(ayysId) && xmlPath1.Contains("案由要素"))
                                            {
                                                j = xmlPath1.LastIndexOf("案由要素");
                                            }
                                            else
                                            {
                                                j = xmlPath1.LastIndexOf(caseCausexml.CC_Name);
                                            }
                                            xmlPath1 = xmlPath1.Substring(j);
                                        }
                                        else
                                        {
                                            //int j = model.AllParentName.LastIndexOf(caseCausexml.CC_Name);
                                            int j = 0;
                                            string ayysId = casecausebLL.GetAyysIDByName(caseCausexml.CC_ID);
                                            if (!string.IsNullOrEmpty(ayysId) && model.AllParentName.Contains("案由要素"))
                                            {
                                                j = model.AllParentName.LastIndexOf("案由要素");
                                            }
                                            else
                                            {
                                                j = model.AllParentName.LastIndexOf(caseCausexml.CC_Name);
                                            }
                                            xmlPa = clicknode.FullPath.Substring(j - 1).Replace("\\", ",");

                                            xmlPath1 = (clicknode.Parent.FullPath.Replace("\\", ",") + "," + oldName).Substring(j);
                                        }
                                        string[] strs1 = xmlPath1.Split(',');
                                        StringBuilder sb1 = new StringBuilder();
                                        foreach (var item in strs1)
                                        {
                                            sb1.Append("/" + item);
                                        }
                                        //原节点路由
                                        string res4 = sb1.ToString();

                                        string[] strs2 = xmlPa.Split(',');
                                        StringBuilder sb2 = new StringBuilder();
                                        foreach (var item in strs2)
                                        {
                                            sb2.Append("/" + item);
                                        }
                                        string res5 = sb2.ToString();

                                        if (!string.IsNullOrEmpty(res4) && !res4.Contains("、") && !res4.Contains("，"))
                                        {

                                            XmlNode objxml = doc.SelectSingleNode(res4);
                                            if (objxml != null)
                                            {
                                                //如果修改的节点为xml属性，则删除旧的属性，然后添加一个新的属性
                                                //如果修改的节点为普通节点，则从父节点移除原来名称节点然后添加新节点
                                                if (editnode != null && editnode.Parent.Text == "属性")
                                                {
                                                    objxml.Attributes.RemoveNamedItem(oldName);
                                                    XmlElement objxml001 = (XmlElement)objxml;
                                                    objxml001.SetAttribute(model.CC_Name, "");
                                                }
                                                else
                                                {
                                                    XmlNode objxml1 = doc.SelectSingleNode(res5);
                                                    XmlElement objElement = doc.CreateElement(model.CC_Name);
                                                    objxml1.AppendChild(objElement);
                                                    objxml1.RemoveChild(objxml);
                                                }
                                            }
                                        }
                                    }
                                    string strres = doc.InnerXml.ToString();
                                    if (!string.IsNullOrEmpty(strres))
                                    {
                                        bool res = casecausebLL.UpdateElementXML(caseCausexml.CC_ID, FormatXML(strres));
                                        if (res)
                                        {
                                            // MsgBox.OK("添加成功，查看请刷新节点树!");
                                        }
                                        else
                                        {
                                            MsgBox.Err("更新xml结构失败！");
                                        }
                                    }
                                }
                            }
                        }
                        //酌定情节维护法定刑配置信息
                        if (model.CC_NodeType == 5)
                        {
                            DataTable dtXFAdjustment = xfPunishimentAdjustmentBll.GetAdjustment(clicknode.Tag.ToString());
                            XF_Punishiment_AdjustmentModel xp = new XF_Punishiment_AdjustmentModel();
                            xp.CC_ID = clicknode.Tag.ToString();
                            xp.PA_SentenceID = cbxSentence.SelectedValue.ToString();
                            xp.PA_influenceTypeID = comboBox2.SelectedValue.ToString();
                            xp.PA_AdjustTypeID = cbxAdjustType.SelectedValue.ToString();
                            if (dtXFAdjustment != null && dtXFAdjustment.Rows.Count > 0)
                            {
                                xfPunishimentAdjustmentBll.UpdateName(xp);
                            }
                            else
                            {
                                xfPunishimentAdjustmentBll.Add(xp);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("修改为xml属性1出错:" + ex.Message);
                        return;
                    }
                }
                /// <summary>
                /// 根据节点树界面修改名称后修改表述关系内容表节点名称
                /// 2018-03-07 需求
                /// </summary>
                if (oldName != Childname2.Text.Trim())
                {
                    try
                    {
                        eml.UpdateCCName(oldName, Childname2.Text.Trim(), clicknode.Tag.ToString());
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("根据节点树界面修改名称后修改表述关系内容表节点名称出错:" + ex.Message);
                        return;
                    }
                    try
                    {
                        regInfoBll.UpdateEIName(oldName, Childname2.Text.Trim(), clicknode.Tag.ToString());
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("根据CCID修改信息单元的名称出错:" + ex.Message);
                        return;
                    }
                }
                //根据案由节点获取xmlPath
                //if (clicknode.FullPath.StartsWith("民事案由")|| clicknode.FullPath.StartsWith("行政执法"))
                //{
                casecausebLL.UpdateXmlPath(caseCausexml.CC_ID);
                //保存地域与违法行为-需求文档：行政执法表述工具优化方案0731.docx
                if (cmbSysDistrict.checkNodeList.Any())
                {
                    Xzzf_DisWfRelBLL disWfRelBll = new Xzzf_DisWfRelBLL();
                    List<Xzzf_DisWfRel> disWfRels = new List<Xzzf_DisWfRel>();
                    cmbSysDistrict.checkNodeList.ForEach(x => disWfRels.Add(new Xzzf_DisWfRel() { RC_ID = newid.JudgeDoc_CreateID("Xzzf_DisWfRel"), CC_District = x, WF_ID = clicknode.Tag.ToString() }));
                    //添加地域与违法行为关系时先删除旧有的关系，不考虑关系与裁量情节的关系，业务添加时进行保证
                    var res1 = disWfRelBll.DelDisWfRelByWfid(clicknode.Tag.ToString());
                    var res = disWfRelBll.InsertDisWfRel(disWfRels);
                }
                else
                {
                    var res1 = new Xzzf_DisWfRelBLL().DelDisWfRelByWfid(clicknode.Tag.ToString());
                }
                MessageBox.Show("节点编辑成功！");

                //节点编辑完成之后重新加载节点树，以清空选择项
                if (!string.IsNullOrEmpty(cmbSysDistrict.Text))
                {
                    cmbSysDistrict.checkNodeList.Clear();
                    LoadDistrictFirst(cmbSysDistrict);
                }
                this.Cursor = Cursors.Arrow;
                //}
                //else //刑事案由等其他案由
                //{
                //    casecausebLL.UpdateXmlPathByXS(casecausebLL.IsParentRealation1(clicknode.Tag.ToString()).CC_ID);
                //}
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存节点失败！" + ex.Message);
                this.Cursor = Cursors.Arrow;
                return;
            }
        }

        /// <summary>
        /// 根据allparentName与节点名称来截取xmlPath
        /// 逻辑：从allparentname中判断是否有案由要素，如果有案由要素从案由下的案由要素开始截取，否则从上一级案由开始
        /// 如果名称为属性则替换掉属性，因为属性为虚节点在xml中没有实际节点，否则替换为@
        /// </summary>
        /// <param name="allParentName"></param>
        /// <param name="ccName"></param>
        /// <returns></returns>
        public string GetXmlPath(string allParentName, string ayName, string ccName)
        {
            int i = 0;
            if (allParentName.Contains("案由要素"))
            {
                i = allParentName.LastIndexOf("案由要素");
            }
            else if (!string.IsNullOrEmpty(ayName))
            {
                i = allParentName.LastIndexOf(ayName);
            }
            string str2 = string.Empty;
            if (ccName == "属性")
            {
                str2 = allParentName.Substring(i).Replace(',', '/').Replace("/属性", "");
            }
            else
            {
                str2 = allParentName.Substring(i).Replace(',', '/').Replace("/属性/", "/@");
            }
            return "/" + str2;
        }


        #endregion

        #region 诉请事实关系XML模板(第十个插页)

        private void AddAttrRelXML_Click(object sender, EventArgs e)
        {
            if (casecausebLL.UpdateAttrRelXML(clicknode.Tag.ToString(), AttrRelXMLText.Text))
            { MessageBox.Show("保存成功!"); }
            else
            {
                MessageBox.Show("保存失败!");
            }
        }

        private void ShowAttrRelXML()
        {
            var dt = casecausebLL.GetSYS_CaseCauseByCCID(clicknode.Tag.ToString());
            AttrRelXMLText.Text = LdFormat.ObjectToString(dt.Rows[0]["AttrRelXML"]);
        }

        #endregion

        #region 诉请与要素关系配置插页  第十一个插页
        /// <summary>
        /// 展示诉请种类列表，通过情形情节节点ID
        /// </summary>
        /// <param name="ccId">通过情形情节节点ID</param>
        private void ShowSuitTypeList(string ccId)
        {
            BindData(ccId);
        }

        /// <summary>
        /// 绑定数据
        /// </summary>
        /// <param name="ccId">情形情节ID</param>
        /// <param name="searchWords">查询关键词</param>
        private void BindData(string ccId, string searchWords = null)
        {
            var dt = xmlLabelSuitTypeRelBll.GetSuitTypeList(ccId, searchWords);
            dgSuitType.AutoGenerateColumns = false;
            dgSuitType.DataSource = dt;

            if (dt != null && dt.Rows.Count > 0)
            {
                //默认取第一条
                var stId = dt.Rows[0]["ST_ID"].ToString();
                var dtRel = xmlLabelSuitTypeRelBll.GetSuitTypeRelList(stId);
                dgSuitTypeXmlRel.AutoGenerateColumns = false;
                dgSuitTypeXmlRel.DataSource = dtRel;
            }
            else
            {
                dgSuitTypeXmlRel.DataSource = new DataTable();
            }
        }


        private void dgSuitType_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (e.RowIndex >= 0)
                {
                    //若行已是选中状态就不再进行设置
                    if (dgSuitType.Rows[e.RowIndex].Selected == false)
                    {
                        dgSuitType.ClearSelection();
                        dgSuitType.Rows[e.RowIndex].Selected = true;
                    }
                    //只选中一行时设置活动单元格
                    if (dgSuitType.SelectedRows.Count == 1)
                    {
                        dgSuitType.CurrentCell = dgSuitType.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    }
                    //弹出操作菜单
                    contextMenuStrip3.Show(MousePosition.X, MousePosition.Y);
                }
            }
        }


        /// <summary>
        /// 单击诉请种类事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgSuitType_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgSuitType.SelectedRows.Count > 0)
            {
                var currentrow = dgSuitType.CurrentRow;
                var stId = dgSuitType.SelectedRows[0].Cells["ST_ID"].Value.ToString();
                var dtRel = xmlLabelSuitTypeRelBll.GetSuitTypeRelList(stId);

                dgSuitTypeXmlRel.AutoGenerateColumns = false;
                dgSuitTypeXmlRel.DataSource = dtRel;
            }

        }




        /// <summary>
        /// 修改诉请种类
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 修改诉请种类ToolStripMenuItem_Click(object sender, EventArgs e)
        {

            FrmEditSutiType frm = new FrmEditSutiType { CcId = clicknode.Tag.ToString() };
            frm.FormClosed += frm_FormClosed;
            var result = frm.ShowDialog();
            if (result == DialogResult.Yes)
            {
                frm.Close();
                ////重新加载诉请与要素关系配置信息
                //BindData(clicknode.Tag.ToString());

            }
        }

        void frm_FormClosed(object sender, FormClosedEventArgs e)
        {
            ShowSuitTypeList(clicknode.Tag.ToString());
        }

        /// <summary>
        /// 添加要素配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 添加要素配置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //获取当前选中行
            var stId = dgSuitType.CurrentRow.Cells["ST_ID"].Value.ToString();

            FrmSuitTypeRel frm = new FrmSuitTypeRel { CcId = clicknode.Tag.ToString(), StId = stId };
            var result = frm.ShowDialog();
            if (result == DialogResult.Yes)
            {
                //重新加载诉请与要素关系配置信息
            }
        }


        /// <summary>
        /// 根据情形情节ID（CCID）获取节点下的诉请要素关系,要素关系配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 修改要素配置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmSuitTypeRelConfig frm = new FrmSuitTypeRelConfig { CcId = clicknode.Tag.ToString() };
            frm.ShowDialog();
            // BindData(clicknode.Tag.ToString());
        }

        /// <summary>
        /// 鼠标按下
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtSuitTypeSearch_MouseDown(object sender, MouseEventArgs e)
        {
            if (txtSuitTypeSearch.Text.Equals("请输入关键字搜索"))
            {
                txtSuitTypeSearch.Text = string.Empty;
            }
        }

        private void txtSuitTypeSearch_MouseLeave(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtSuitTypeSearch.Text))
            {
                txtSuitTypeSearch.Text = @"请输入关键字搜索";
            }
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSuitTypeSearch_Click(object sender, EventArgs e)
        {
            //if (string.IsNullOrEmpty(txtSuitTypeSearch.Text) || txtSuitTypeSearch.Text.Equals("请输入关键字搜索"))
            //{
            //    MsgBox.Warn("请输入关键字");
            //    return;
            //}
            //else
            //{

            BindData(clicknode.Tag.ToString(), txtSuitTypeSearch.Text.Equals("请输入关键字搜索") ? string.Empty : txtSuitTypeSearch.Text);
            //}
        }

        #endregion

        #region 要素与证据关系配置 第十二个插页
        /// <summary>
        /// 展示要素证据关系列表，通过情形情节节点ID
        /// </summary>
        /// <param name="ccId">通过情形情节节点ID</param>
        private void ShowZhengJuList(string ccId, string search = "")
        {
            var dt = sysCTDT.GetSysCaseType(ccId);
            if (!string.IsNullOrEmpty(search) && dt.Select(" CD_Name like '%" + search.Trim() + "%'  ").Length > 0)
            {
                dt = dt.Select(" CD_Name like '%" + search.Trim() + "%'  ").CopyToDataTable<DataRow>();
            }
            dgvZhengJu.AutoGenerateColumns = false;
            dgvZhengJu.DataSource = PublicMethod.AddDataTableNum(dt);

            if (dt != null && dt.Rows.Count > 0)
            {
                //默认取第一条
                var cdId = dt.Rows[0]["CD_ID"].ToString();
                DataTable dt1 = sce.GetSysCaseCauseElementData(cdId, clicknode.Text);
                dgvYSRelation.AutoGenerateColumns = false;
                dgvYSRelation.DataSource = dt1;
            }
            else
            {
                dgvYSRelation.DataSource = new DataTable();
            }
        }

        private void txbYSZJKey_MouseLeave(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txbYSZJKey.Text))
            {
                txbYSZJKey.Text = @"请输入关键字搜索";
            }
        }

        private void txbYSZJKey_MouseDown(object sender, MouseEventArgs e)
        {
            if (txbYSZJKey.Text.Equals("请输入关键字搜索"))
            {
                txbYSZJKey.Text = string.Empty;
            }
        }

        /// <summary>
        /// 证据配置区查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnYSZJFind_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txbYSZJKey.Text.Trim()))
            {
                MessageBox.Show("请输入关键字后在点击查询按钮进行查询操作！");
                return;
            }
            else
            {
                ShowZhengJuList(clicknode.Tag.ToString(), txbYSZJKey.Text.Trim());
            }
        }

        /// <summary>
        /// 证据配置区单击鼠标事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvZhengJu_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (e.RowIndex >= 0)
                {
                    //若行已是选中状态就不再进行设置
                    if (dgvZhengJu.Rows[e.RowIndex].Selected == false)
                    {
                        dgvZhengJu.ClearSelection();
                        dgvZhengJu.Rows[e.RowIndex].Selected = true;
                    }
                    //只选中一行时设置活动单元格
                    if (dgvZhengJu.SelectedRows.Count == 1)
                    {
                        dgvZhengJu.CurrentCell = dgvZhengJu.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    }
                    //弹出操作菜单
                    contextMenuStrip5.Show(MousePosition.X, MousePosition.Y);
                }
            }
        }

        /// <summary>
        /// 证据配置区鼠标单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvZhengJu_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvZhengJu.SelectedRows.Count > 0)
            {
                var currentrow = dgvZhengJu.CurrentRow;
                var cdId = dgvZhengJu.SelectedRows[0].Cells["CD_ID"].Value.ToString();
                var dtRel = sce.GetSysCaseCauseElementData(cdId, clicknode.Text);

                dgvYSRelation.AutoGenerateColumns = false;
                dgvYSRelation.DataSource = dtRel;
            }
        }

        /// <summary>
        /// 添加要素配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 添加要素配置ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            //获取当前选中行
            var cdID = dgvZhengJu.CurrentRow.Cells["CD_ID"].Value.ToString();

            frmZhengJuConfig frm = new frmZhengJuConfig(0) { CcId = clicknode.Tag.ToString(), CdID = cdID, CCName = clicknode.Text };
            var result = frm.ShowDialog();
            if (result == DialogResult.Yes)
            {
                var dtRel = sce.GetSysCaseCauseElementData(cdID, clicknode.Text);

                dgvYSRelation.DataSource = dtRel;
            }
        }

        /// <summary>
        /// 修改要素配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 修改要素配置ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            var cdID = dgvZhengJu.CurrentRow.Cells["CD_ID"].Value.ToString();
            var cdName = dgvZhengJu.CurrentRow.Cells["CD_Name"].Value.ToString();

            FrmZhengJuDetailConfig frm = new FrmZhengJuDetailConfig(0) { CDName = cdName, CDID = cdID, CCName = clicknode.Text.Trim() };
            var result = frm.ShowDialog();
            if (result == DialogResult.Yes)
            {
                var dtRel = sce.GetSysCaseCauseElementData(cdID, clicknode.Text);

                dgvYSRelation.DataSource = dtRel;
            }
        }
        #endregion

        #region 要素与争议焦点关系配置
        /// <summary>
        /// 展示要素争议焦点列表，通过情形情节节点ID
        /// </summary>
        /// <param name = "ccId" > 通过情形情节节点ID </ param >
        private void ShowFocusList(string ccId, string search = "")
        {
            DataTable dt = casecausebLL.GetAllChild1(ccId);
            if (dt != null && dt.Rows.Count > 0 && dt.Select("  CC_NodeType=16 ").Length > 0)
            {
                dt = dt.Select("  CC_NodeType=16 ").CopyToDataTable<DataRow>();
                if (!string.IsNullOrEmpty(search) && dt.Select(" CC_Name like '%" + search.Trim() + "%'  ").Length > 0)
                {
                    dt = dt.Select(" CC_Name like '%" + search.Trim() + "%'  ").CopyToDataTable<DataRow>();
                }
                dgvFocus.AutoGenerateColumns = false;
                dgvFocus.DataSource = PublicMethod.AddDataTableNum(dt);
                if (dt != null && dt.Rows.Count > 0)
                {
                    //默认取第一条
                    var cc_Id = dt.Rows[0]["CC_ID"].ToString();
                    DataTable dt1 = sysArgumentElementBll.GetSysArgumentElementRelData(cc_Id);
                    dgvFocusData.AutoGenerateColumns = false;
                    dgvFocusData.DataSource = dt1;
                }
                else
                {
                    dgvFocusData.DataSource = new DataTable();
                }
            }
        }

        private void txtFocusKey_MouseLeave(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtFocusKey.Text))
            {
                txtFocusKey.Text = @"请输入关键字搜索";
            }
        }

        private void txtFocusKey_MouseDown(object sender, MouseEventArgs e)
        {
            if (txtFocusKey.Text.Equals("请输入关键字搜索"))
            {
                txtFocusKey.Text = string.Empty;
            }
        }

        /// <summary>
        /// 争议焦点配置区查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFocus_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtFocusKey.Text.Trim()))
            {
                MessageBox.Show("请输入关键字后在点击查询按钮进行查询操作！");
                return;
            }
            else
            {
                ShowFocusList(clicknode.Tag.ToString(), txtFocusKey.Text.Trim());
            }
        }

        /// <summary>
        /// 争议焦点配置区单击鼠标事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvFocus_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (e.RowIndex >= 0)
                {
                    //若行已是选中状态就不再进行设置
                    if (dgvFocus.Rows[e.RowIndex].Selected == false)
                    {
                        dgvFocus.ClearSelection();
                        dgvFocus.Rows[e.RowIndex].Selected = true;
                    }
                    //只选中一行时设置活动单元格
                    if (dgvFocus.SelectedRows.Count == 1)
                    {
                        dgvFocus.CurrentCell = dgvFocus.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    }
                    //弹出操作菜单
                    contextMenuStrip6.Show(MousePosition.X, MousePosition.Y);
                }
            }
        }

        /// <summary>
        /// 争议焦点配置区单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvFocus_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvFocus.SelectedRows.Count > 0)
            {
                var currentrow = dgvFocus.CurrentRow;
                var ccId = dgvFocus.SelectedRows[0].Cells["ccID1"].Value.ToString();
                DataTable dt1 = sysArgumentElementBll.GetSysArgumentElementRelData(ccId);
                if (dt1 != null && dt1.Rows.Count > 0)
                {
                    dgvFocusData.AutoGenerateColumns = false;
                    dgvFocusData.DataSource = dt1;
                }
                else
                {
                    dgvFocusData.DataSource = new DataTable();
                }
            }
        }

        /// <summary>
        /// 添加要素配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 添加要素配置ToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            var ccId = dgvFocus.SelectedRows[0].Cells["ccID1"].Value.ToString();
            frmZhengJuConfig frm = new frmZhengJuConfig(1) { CcId = clicknode.Tag.ToString(), CcConfigId = ccId };
            var result = frm.ShowDialog();
            if (result == DialogResult.Yes)
            {
                var dtRel = sysArgumentElementBll.GetSysArgumentElementRelData(ccId);

                dgvFocusData.DataSource = dtRel;
            }
        }

        /// <summary>
        /// 修改要素配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 修改要素配置ToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            var ccId = dgvFocus.SelectedRows[0].Cells["ccID1"].Value.ToString();
            var ccName = dgvFocus.SelectedRows[0].Cells["CCName"].Value.ToString();
            FrmZhengJuDetailConfig frm = new FrmZhengJuDetailConfig(1) { ccID = ccId, ccName = ccName };
            var result = frm.ShowDialog();
            if (result == DialogResult.Yes)
            {
                var dtRel = sysArgumentElementBll.GetSysArgumentElementRelData(ccId);

                dgvFocusData.DataSource = dtRel;
            }
        }

        #endregion


        #region 法定刑档次信息
        private void LoadFDXData()
        {
            LoadZXZL();
            LoadFJXZL();
            LoadFJXSYFS();
            LoadPunishmentData();
            ClearFDX();
            punishMent = new Punishment();
        }


        private void LoadPunishmentData()
        {
            if (!string.IsNullOrEmpty(clicknode.Tag.ToString()))
            {
                DataTable dt = xfPunishmentGradeBLL.GetPunishmentData(clicknode.Tag.ToString());
                if (dt != null && dt.Rows.Count > 0)
                {
                    dgvZX.DataSource = dt;
                }
                else
                {
                    DataTable dtt = (DataTable)dgvZX.DataSource;
                    if (dtt != null)
                    { dtt.Rows.Clear(); }
                    dgvZX.DataSource = dtt;
                }
            }
        }

        #region 加载主刑种类
        /// <summary>
        /// 加载主刑种类
        /// </summary>
        private void LoadZXZL()
        {
            DataTable dtt = new DataTable();
            dtt.Columns.Add("Id");
            dtt.Columns.Add("Name");
            SYS_ArgumentType sat = nodetree_argumenttypebll.GetMatchKeyWord("MainCrimeTypeID");
            if (!string.IsNullOrEmpty(sat.AT_MatchKeyWord))
            {
                string[] strs = sat.AT_MatchKeyWord.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string str in strs)
                {
                    string[] str1 = str.Split('=');
                    if (str1.Length > 0)
                    {
                        DataRow dr = dtt.NewRow();
                        dr["Id"] = str1[0].ToString();
                        dr["Name"] = str1[1].ToString();
                        dtt.Rows.Add(dr);
                    }
                }
                if (dtt.Rows.Count > 0)
                {
                    DataRow dr = dtt.NewRow();
                    dr["Id"] = "0";
                    dr["Name"] = ""; ;
                    dtt.Rows.InsertAt(dr, 0);
                    cmbZXZL.DataSource = dtt;
                    cmbZXZL.DisplayMember = "Name";
                    cmbZXZL.ValueMember = "Id";
                    //if (dtXFAdjustment != null && dtXFAdjustment.Rows.Count > 0 && !string.IsNullOrEmpty(dtXFAdjustment.Rows[0]["PA_SentenceID"].ToString()))
                    //{
                    //    cbxSentence.SelectedValue = dtXFAdjustment.Rows[0]["PA_SentenceID"].ToString();
                    //}
                }
            }
        }
        #endregion

        #region 加载附加刑种类
        /// <summary>
        /// 加载附加刑种类
        /// </summary>
        private void LoadFJXZL()
        {
            DataTable dtt = new DataTable();
            dtt.Columns.Add("Id");
            dtt.Columns.Add("Name");
            SYS_ArgumentType sat = nodetree_argumenttypebll.GetMatchKeyWord("AddTypeID");
            if (!string.IsNullOrEmpty(sat.AT_MatchKeyWord))
            {
                string[] strs = sat.AT_MatchKeyWord.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string str in strs)
                {
                    string[] str1 = str.Split('=');
                    if (str1.Length > 0)
                    {
                        DataRow dr = dtt.NewRow();
                        dr["Id"] = str1[0].ToString();
                        dr["Name"] = str1[1].ToString();
                        dtt.Rows.Add(dr);
                    }
                }
                if (dtt.Rows.Count > 0)
                {
                    DataRow dr = dtt.NewRow();
                    dr["Id"] = "0";
                    dr["Name"] = ""; ;
                    dtt.Rows.InsertAt(dr, 0);
                    cmbFjxZL1.DataSource = dtt;
                    DataTable dtt1 = dtt.Copy();
                    cmbFjxZL2.DataSource = dtt1;
                    DataTable dtt2 = dtt.Copy();
                    cmbFjxZL3.DataSource = dtt2;
                    cmbFjxZL1.DisplayMember = cmbFjxZL2.DisplayMember = cmbFjxZL3.DisplayMember = "Name";
                    cmbFjxZL1.ValueMember = cmbFjxZL2.ValueMember = cmbFjxZL3.ValueMember = "Id";

                    //if (dtXFAdjustment != null && dtXFAdjustment.Rows.Count > 0 && !string.IsNullOrEmpty(dtXFAdjustment.Rows[0]["PA_SentenceID"].ToString()))
                    //{
                    //    cbxSentence.SelectedValue = dtXFAdjustment.Rows[0]["PA_SentenceID"].ToString();
                    //}
                }
            }
        }
        #endregion

        #region 加载附加刑适用方式
        /// <summary>
        /// 加载附加刑适用方式
        /// </summary>
        private void LoadFJXSYFS()
        {
            DataTable dtt = new DataTable();
            dtt.Columns.Add("Id");
            dtt.Columns.Add("Name");
            SYS_ArgumentType sat = nodetree_argumenttypebll.GetMatchKeyWord("ApplicationID");
            if (!string.IsNullOrEmpty(sat.AT_MatchKeyWord))
            {
                string[] strs = sat.AT_MatchKeyWord.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string str in strs)
                {
                    string[] str1 = str.Split('=');
                    if (str1.Length > 0)
                    {
                        DataRow dr = dtt.NewRow();
                        dr["Id"] = str1[0].ToString();
                        dr["Name"] = str1[1].ToString();
                        dtt.Rows.Add(dr);
                    }
                }
                if (dtt.Rows.Count > 0)
                {
                    DataRow dr = dtt.NewRow();
                    dr["Id"] = "0";
                    dr["Name"] = ""; ;
                    dtt.Rows.InsertAt(dr, 0);
                    cmbFjxSY1.DataSource = dtt;
                    cmbFjxSY2.DataSource = dtt.Copy();
                    cmbFjxSY3.DataSource = dtt.Copy();
                    cmbFjxSY1.DisplayMember = cmbFjxSY2.DisplayMember = cmbFjxSY3.DisplayMember = "Name";
                    cmbFjxSY1.ValueMember = cmbFjxSY2.ValueMember = cmbFjxSY3.ValueMember = "Id";
                    //if (dtXFAdjustment != null && dtXFAdjustment.Rows.Count > 0 && !string.IsNullOrEmpty(dtXFAdjustment.Rows[0]["PA_SentenceID"].ToString()))
                    //{
                    //    cbxSentence.SelectedValue = dtXFAdjustment.Rows[0]["PA_SentenceID"].ToString();
                    //}
                }
            }
        }
        #endregion

        #endregion
        #endregion

        #region
        public void GetFDXRelationInfo()
        {
            LoadDCInfo();
            LoadQXInfo();
            LoadFXD();
        }

        /// <summary>
        /// 加载档次信息
        /// </summary>
        private void LoadDCInfo()
        {
            if (!string.IsNullOrEmpty(clicknode.Tag.ToString()))
            {
                DataTable dt = xfPunishmentGradeBLL.GetPunishmentGrade(clicknode.Tag.ToString());
                if (dt != null && dt.Rows.Count > 0)
                {
                    cmbDCSelect.DataSource = dt;
                    cmbDCSelect.DisplayMember = "PG_Grade";
                    cmbDCSelect.ValueMember = "PG_ID";
                }
            }
        }

        /// <summary>
        /// 加载法定刑关系信息
        /// </summary>
        private void LoadFXD()
        {
            DataTable dt = xfPunishmentGradeBLL.GetFDXRelationData(clicknode.Tag.ToString());
            if (dt != null && dt.Rows.Count > 0)
            {
                dt.Columns.Add("CCName");
                foreach (DataRow item in dt.Rows)
                {
                    if (!string.IsNullOrEmpty(item["PR_groupID"].ToString()))
                    {
                        DataTable dt1 = xrsg.GetQxData(item["PR_groupID"].ToString());
                        if (dt1 != null && dt1.Rows.Count > 0)
                        {
                            //DataTable dtNew = casecausebLL.GetAllChild(clicknode.Tag.ToString());
                            StringBuilder name = new StringBuilder();
                            foreach (DataRow ite in dt1.Rows)
                            {
                                name.Append(ite["CC_Name"] + ";");
                            }
                            if (!string.IsNullOrEmpty(name.ToString().Trim()))
                            {
                                string nam = name.ToString().Trim().Remove(name.ToString().Trim().Length - 1, 1);
                                item["CCName"] = nam;
                            }
                        }
                    }
                }
                dt = PublicMethod.AddDataTableNum(dt);
                dgvFDXR.DataSource = dt;
            }
            else
            {
                PublicMethod.ClearDataGridViewData(dgvFDXR);
            }
        }

        /// <summary>
        /// 加载情形与法定刑关系信息
        /// </summary>
        private void LoadQXInfo()
        {
            checkcbSituation1.Text = checkcbSituation2.Text = checkcbSituation3.Text = checkcbSituation4.Text = "";
            checkcbSituation1.checkNodeList.Clear();
            checkcbSituation2.checkNodeList.Clear();
            checkcbSituation3.checkNodeList.Clear();
            checkcbSituation4.checkNodeList.Clear();
            checkcbSituation1.TreeView.Nodes.Clear();
            checkcbSituation2.TreeView.Nodes.Clear();
            checkcbSituation3.TreeView.Nodes.Clear();
            checkcbSituation4.TreeView.Nodes.Clear();
            string ccid = casecausebLL.GetQXccID(clicknode.Tag.ToString());
            if (!string.IsNullOrEmpty(ccid))
            {
                dtFDXNode = casecausebLL.GetAllChild(ccid);
                if (dtFDXNode != null && dtFDXNode.Rows.Count > 0 && dtFDXNode.Select(" CC_ParentID='" + ccid + "' ").Length > 0)
                {
                    DataRow[] drs = dtFDXNode.Select(" CC_ParentID='" + ccid + "' ", " CC_SerialNumb ");
                    foreach (var item in drs)
                    {
                        TreeNode node = new TreeNode();
                        node.Text = item["CC_Name"].ToString();
                        node.Tag = item["CC_ID"].ToString();
                        if (dtFDXNode.Select(" CC_ParentID='" + node.Tag + "' ").Length > 0)
                        {
                            node.Nodes.Add(new TreeNode());
                        }
                        checkcbSituation1.TreeView.Nodes.Add(node);
                        TreeNode node1 = (TreeNode)node.Clone();
                        checkcbSituation2.TreeView.Nodes.Add(node1);
                        TreeNode node2 = (TreeNode)node.Clone();
                        checkcbSituation3.TreeView.Nodes.Add(node2);
                        TreeNode node3 = (TreeNode)node.Clone();
                        checkcbSituation4.TreeView.Nodes.Add(node3);
                    }
                    TreeNode node01 = new TreeNode();
                    node01.Text = "请选择";
                    node01.Tag = "";
                    checkcbSituation1.TreeView.Nodes.Insert(0, node01);
                    TreeNode node02 = (TreeNode)node01.Clone();
                    checkcbSituation2.TreeView.Nodes.Insert(0, node02);
                    TreeNode node03 = (TreeNode)node01.Clone();
                    checkcbSituation3.TreeView.Nodes.Insert(0, node03);
                    TreeNode node04 = (TreeNode)node01.Clone();
                    checkcbSituation4.TreeView.Nodes.Insert(0, node04);

                    //checkcbSituation1.Items.Clear();
                    //checkcbSituation2.Items.Clear();
                    //checkcbSituation3.Items.Clear();
                    //checkcbSituation4.Items.Clear();
                    //foreach (DataRow dr in dtFDXNode.Rows)
                    //{
                    //    ComboxItem ci = new ComboxItem(dr["CC_Name"].ToString(), dr["CC_ID"].ToString());
                    //    checkcbSituation1.Items.Add(ci);
                    //    checkcbSituation1.Text = "请选择";
                    //    checkcbSituation2.Items.Add(ci);
                    //    checkcbSituation2.Text = "请选择";
                    //    checkcbSituation3.Items.Add(ci);
                    //    checkcbSituation3.Text = "请选择";
                    //    checkcbSituation4.Items.Add(ci);
                    //    checkcbSituation4.Text = "请选择";
                    //}

                }
            }

        }
        #endregion


        #region 接口方法
        public void CloseForm()
        {

        }
        // 显示进度条
        // 显示进度条
        public void ShowProgress(int MaxCount, int CurrentCount)
        {
            if (progressBar1.InvokeRequired == false)
            {
                if (CurrentCount < MaxCount)
                {
                    progressBar1.Value = CurrentCount;
                    progressBar1.Maximum = MaxCount;

                    progressBar1.Text = CurrentCount + "/" + MaxCount;
                    lblCount.Text = "当前" + CurrentCount + "条";
                }
                else if (CurrentCount == MaxCount)
                {
                    progressBar1.Value = CurrentCount;
                    progressBar1.Maximum = MaxCount;
                    progressBar1.Text = CurrentCount + "/" + MaxCount;
                    lblCount.Text = "已完成!";
                    workThread = null;
                    StaticCacheBLL.plotchildDict = new Dictionary<string, DataTable>();//清除规则缓存
                }
            }
            else
            {
                ProcessShow processshow = ShowProgress;
                Invoke(processshow, MaxCount, CurrentCount);
            }

        }

        #endregion

        #region 添加要素
        /// <summary>
        /// 添加要素
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddElement_Click(object sender, EventArgs e)
        {
            var addElementDiction = new Dictionary<string, string>();

            var dr = MsgBox.Ask("是否立即处理?", "加工要素");
            var dp = DataProcess.Default;
            foreach (var node in NodeList)
            {
                if (node.Checked)
                {
                    if (!addElementDiction.ContainsKey(node.Tag.ToString()))
                    {
                        addElementDiction.Add(node.Tag.ToString(), node.Text);
                    }

                }
            }

            if (dr == DialogResult.Yes)//如果点击“确定”按钮
            {
                dp.Start_Again(addElementDiction);
            }

        }
        #endregion

        #region 定位
        /// <summary>
        /// 定位开始索引
        /// </summary>
        private int locationIndex;
        /// <summary>
        /// 匹配关键字的集合
        /// </summary>
        private MatchCollection _matchCollection;
        /// <summary>
        /// 定位
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LocateWord_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (string.IsNullOrEmpty(txtKeyword.Text.Trim())) return;

            txt_ArgumentTypeXml.SelectionStart = 0;
            txt_ArgumentTypeXml.SelectionLength = txt_ArgumentTypeXml.Text.Length;
            txt_ArgumentTypeXml.SelectionBackColor = Color.White;
            var r = new System.Text.RegularExpressions.Regex(txtKeyword.Text.Trim()); //定义一个Regex对象实例
            var mc = r.Matches(txt_ArgumentTypeXml.Text);
            //符合条件个数
            lblKeywordCount.Text = mc.Count.ToString();
            //当前第一条
            lblKeywordsCurrent.Text = 1.ToString();
            _matchCollection = mc;
            for (var i = 0; i < mc.Count; i++) //在输入字符串中找到所有匹配
            {
                var start = mc[i].Index; //记录匹配字符的位置
                var length = (txtKeyword.Text.Trim()).Length;
                txt_ArgumentTypeXml.SelectionStart = start;
                txt_ArgumentTypeXml.SelectionLength = length;
                txt_ArgumentTypeXml.SelectionBackColor = Color.Red;
            }

            //定位到指定满足条件的第一个文字上   add by zhangpeng
            var firstIndex = txt_ArgumentTypeXml.Find(txtKeyword.Text.Trim());
            //查询不到关键字则提示后直接退出
            if (firstIndex == -1)
            {
                MsgBox.Warn("查无此关键词");
                return;
            }

            txt_ArgumentTypeXml.Focus();
            txt_ArgumentTypeXml.SelectionStart = firstIndex;
            txt_ArgumentTypeXml.ScrollToCaret();
            locationIndex = 0;

        }


        /// <summary>
        /// 下一个关键词定位
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lblNext_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (string.IsNullOrEmpty(txtKeyword.Text))
            {
                MsgBox.Warn("请输入关键词!");
                return;
            }
            if (_matchCollection == null || _matchCollection.Count == 0)
            {
                MsgBox.Warn("请先定位!");
                return;
            }

            if (_matchCollection.Count > (locationIndex + 1))
            {
                locationIndex++;
                var start = _matchCollection[locationIndex].Index;
                var length = (txtKeyword.Text.Trim()).Length;
                txt_ArgumentTypeXml.SelectionStart = start;
                txt_ArgumentTypeXml.SelectionLength = length;
                txt_ArgumentTypeXml.Focus();
                txt_ArgumentTypeXml.ScrollToCaret();
                //当前第几条
                lblKeywordsCurrent.Text = (locationIndex + 1).ToString();
            }
            else
            {
                MsgBox.Warn("已经是最后一个");
            }


        }

        /// <summary>
        /// 上一条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lblKeywordsPre_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (string.IsNullOrEmpty(txtKeyword.Text))
            {
                MsgBox.Warn("请输入关键词!");
                return;
            }
            if (_matchCollection == null || _matchCollection.Count == 0)
            {
                MsgBox.Warn("请先定位!");
                return;
            }
            if (0 <= (locationIndex - 1))
            {
                locationIndex--;
                var start = _matchCollection[locationIndex].Index;
                var length = (txtKeyword.Text.Trim()).Length;
                txt_ArgumentTypeXml.SelectionStart = start;
                txt_ArgumentTypeXml.SelectionLength = length;
                txt_ArgumentTypeXml.Focus();
                txt_ArgumentTypeXml.ScrollToCaret();
                //当前第几条
                lblKeywordsCurrent.Text = (locationIndex + 1).ToString();

            }
            else
            {
                MsgBox.Warn("已经是第一个");
            }
        }

        #endregion

        #region 标记同案节点
        private void ColorCommonCase_Click(object sender, EventArgs e)
        {
            var dt = new DataTable();
            if (ISCommonCase == 0)
            {
                ISCommonCase = 1;
                foreach (var node in NodeList)
                {
                    dt = casecausebLL.GetSYS_CaseCauseByCCID(node.Tag.ToString());
                    if (dt.Rows.Count > 0)
                    {
                        if (dt.Rows[0]["CC_CommonCase"].ToString() == "1")
                            node.ForeColor = Color.Blue;
                        if (dt.Rows[0]["CC_CommonCase"].ToString() == "2")
                            node.ForeColor = Color.Green;
                    }
                }
            }
            else
            {
                ISCommonCase = 0;
                foreach (var node in NodeList)
                {
                    node.ForeColor = Color.Black;
                }
            }
        }
        #endregion

        #region 要素属性数据区点击事件
        private void GV_ArgumentType_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            argumenttypeModel = new SYS_ArgumentType();
            if (e.RowIndex != -1)
            {
                argumenttypeModel.AT_CauseID = getAT_CauseID();
                argumenttypeModel.AT_ID = GV_ArgumentType.Rows[e.RowIndex].Cells["AT_ID"].Value.ToString();
                argumenttypeModel.AT_Code = GV_ArgumentType.Rows[e.RowIndex].Cells["AT_Code"].Value.ToString();
                argumenttypeModel.AT_Name = GV_ArgumentType.Rows[e.RowIndex].Cells["AT_Name"].Value.ToString();
                argumenttypeModel.AT_MatchKeyWord = GV_ArgumentType.Rows[e.RowIndex].Cells["AT_MatchKeyWord"].Value.ToString();
                MatchKeyWordText.Text = argumenttypeModel.AT_MatchKeyWord.Replace("\r", "").Replace(";", ";\n").Replace("；", "；\n");
                RowIndex = e.RowIndex;
            }
        }
        #endregion

        #region 添加来源默认配置
        /// <summary>
        /// 添加来源默认配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDefaultSource_Click(object sender, EventArgs e)
        {
            //添加默认来源
            FrmSourceDefaultSetting fs = new FrmSourceDefaultSetting(0);
            fs.ClickNode = clicknode;
            var dialogResult = fs.ShowDialog();
            if (dialogResult == DialogResult.Yes)
            {
                ShowSource(clicknode.Tag.ToString());
                fs.Close();
            }

        }
        #endregion

        #region 批量修改节点类型
        /// <summary>
        /// 批量修改节点类型
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUpdateNodeType_Click(object sender, EventArgs e)
        {
            //1.当案由是民事案由时，该批量修改节点类型功能可用
            string cc_Id = clicknode.Tag.ToString();

            #region 修改争议焦点要素下的节点类型
            if (!string.IsNullOrEmpty(cc_Id))
            {
                if (casecausebLL.IsCivilCase(cc_Id))
                {
                    //倒数一级节点类型变为裁判结果（字典值为22）倒数二级变为裁判理由（字典值为17）倒数三级变为争议焦点（字典值为16）其他节点变为争议焦点分类（字典值为15）
                    //构造倒数一级表
                    DataTable lastDataTable = new DataTable();
                    lastDataTable.Columns.Add("CC_ID");
                    //构造倒数二级表
                    DataTable SecondDataTable = new DataTable();
                    SecondDataTable.Columns.Add("CC_ID");
                    //构造倒数三级表
                    DataTable ThirdDataTable = new DataTable();
                    ThirdDataTable.Columns.Add("CC_ID");
                    //构造倒数四级表
                    DataTable FourDataTable = new DataTable();
                    FourDataTable.Columns.Add("CC_ID");

                    //其他节点表
                    DataTable OtherDataTable = new DataTable();
                    OtherDataTable.Columns.Add("CC_ID");

                    StringBuilder str = new StringBuilder();
                    bool result = false;
                    //获取该节点下争议焦点要素下的CC_ID集合
                    DataSet ds = casecausebLL.GetDisputeElementData(cc_Id);
                    if (ds != null && ds.Tables.Count > 0)
                    {
                        string disputeElement = "";
                        if (ds.Tables[1] != null && ds.Tables[1].Rows.Count > 0)
                        {
                            disputeElement = ds.Tables[1].Rows[0][0].ToString();
                            DataTable disputeTable = ds.Tables[0];
                            if (disputeTable != null && disputeTable.Rows.Count > 0)
                            {
                                foreach (DataRow dr in disputeTable.Rows)
                                {
                                    //ALL_ParentID
                                    string node = dr[3].ToString();
                                    int i = node.LastIndexOf(',');
                                    //最后一级ccid
                                    string lastCCId = node.Substring(i + 1);
                                    //是最后一级节点
                                    if (casecausebLL.IsLastNode(lastCCId))
                                    {
                                        DataRow lastDr = lastDataTable.NewRow();
                                        lastDr[0] = lastCCId;
                                        lastDataTable.Rows.Add(lastDr);

                                        int j = node.IndexOf(disputeElement);
                                        //争议焦点下的路径
                                        string nodestr = node.Substring(j + disputeElement.Length + 1).Insert(0, ",");

                                        //获取倒数二级节点
                                        string str1 = nodestr.Replace("," + lastCCId, "");
                                        int jj = str1.LastIndexOf(',');
                                        string sencondCCId = str1.Substring(jj + 1);

                                        DataRow secondDr = SecondDataTable.NewRow();
                                        secondDr[0] = sencondCCId;
                                        if (SecondDataTable.Select("CC_ID='" + sencondCCId + "'").Length == 0)
                                        {
                                            SecondDataTable.Rows.Add(secondDr);
                                        }
                                        //else if (SecondDataTable.Select("CC_ID='" + sencondCCId + "'").Length > 0 && ThirdDataTable.Select("CC_ID='" + sencondCCId + "'").Length > 0)
                                        //{
                                        //    MsgBox.Err("CC_ID为"+sencondCCId+"的节点既属于倒数第二级节点，又属于倒数第三级节点！");
                                        //    return;
                                        //}

                                        //获取倒数三级节点
                                        string str2 = str1.Replace("," + sencondCCId, "");
                                        if (!string.IsNullOrEmpty(str2))
                                        {
                                            int jjj = str2.LastIndexOf(',');
                                            string thirdCCId = str2.Substring(jjj + 1);

                                            DataRow thirdDr = ThirdDataTable.NewRow();
                                            thirdDr[0] = thirdCCId;
                                            if (ThirdDataTable.Select("CC_ID='" + thirdCCId + "'").Length == 0)
                                            {
                                                ThirdDataTable.Rows.Add(thirdDr);
                                            }
                                            if ((ThirdDataTable.Select("CC_ID='" + thirdCCId + "'").Length > 0 && SecondDataTable.Select("CC_ID='" + thirdCCId + "'").Length > 0) || (ThirdDataTable.Select("CC_ID='" + thirdCCId + "'").Length > 0 && FourDataTable.Select("CC_ID='" + thirdCCId + "'").Length > 0) || (FourDataTable.Select("CC_ID='" + thirdCCId + "'").Length > 0 && SecondDataTable.Select("CC_ID='" + thirdCCId + "'").Length > 0))
                                            {
                                                string ccName = disputeTable.Select("CC_ID='" + thirdCCId + "'")[0]["CC_Name"].ToString();
                                                MsgBox.Err("CC_ID为" + thirdCCId + ",名称为" + ccName + "的节点层级不一致，请修改后再试！");
                                                return;
                                            }
                                            //获取倒数四级节点
                                            string str3 = str2.Replace("," + thirdCCId, "");
                                            if (!string.IsNullOrEmpty(str3))
                                            {
                                                int jjjj = str3.LastIndexOf(',');
                                                string fourCCId = str3.Substring(jjjj + 1);

                                                DataRow fourDr = FourDataTable.NewRow();
                                                fourDr[0] = fourCCId;
                                                if (FourDataTable.Select("CC_ID='" + fourCCId + "'").Length == 0)
                                                {
                                                    FourDataTable.Rows.Add(fourDr);
                                                }
                                                if ((ThirdDataTable.Select("CC_ID='" + fourCCId + "'").Length > 0 && FourDataTable.Select("CC_ID='" + fourCCId + "'").Length > 0) || (SecondDataTable.Select("CC_ID='" + fourCCId + "'").Length > 0 && FourDataTable.Select("CC_ID='" + fourCCId + "'").Length > 0) || (SecondDataTable.Select("CC_ID='" + fourCCId + "'").Length > 0 && ThirdDataTable.Select("CC_ID='" + fourCCId + "'").Length > 0))
                                                {
                                                    string ccName = disputeTable.Select("CC_ID='" + fourCCId + "'")[0]["CC_Name"].ToString();
                                                    MsgBox.Err("CC_ID为" + fourCCId + ",名称为" + ccName + "的节点层级不一致，请修改后再试！");
                                                    return;
                                                }

                                                string str4 = str3.Replace("," + fourCCId, "");
                                                //中间节点
                                                string[] otherNodes = str4.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                                                if (otherNodes.Length > 0)
                                                {
                                                    foreach (string arNode in otherNodes)
                                                    {
                                                        DataRow otherDr = OtherDataTable.NewRow();
                                                        otherDr[0] = arNode;
                                                        if (OtherDataTable.Select("CC_ID='" + arNode + "'").Length == 0)
                                                        {
                                                            if ((OtherDataTable.Select("CC_ID='" + arNode + "'").Length > 0 && FourDataTable.Select("CC_ID='" + arNode + "'").Length > 0) || (OtherDataTable.Select("CC_ID='" + arNode + "'").Length > 0 && ThirdDataTable.Select("CC_ID='" + arNode + "'").Length > 0) || (SecondDataTable.Select("CC_ID='" + arNode + "'").Length > 0 && OtherDataTable.Select("CC_ID='" + arNode + "'").Length > 0))
                                                            {
                                                                string ccName = disputeTable.Select("CC_ID='" + arNode + "'")[0]["CC_Name"].ToString();
                                                                MsgBox.Err("CC_ID为" + arNode + ",名称为" + ccName + "的节点层级不一致，请修改后再试！");
                                                                return;
                                                            }
                                                            OtherDataTable.Rows.Add(otherDr);
                                                        }
                                                    }
                                                }
                                            }
                                        }



                                    }
                                }
                                int countNum = lastDataTable.Rows.Count + SecondDataTable.Rows.Count + ThirdDataTable.Rows.Count + FourDataTable.Rows.Count + OtherDataTable.Rows.Count;

                                //处理倒数一级节点
                                if (lastDataTable != null && lastDataTable.Rows.Count > 0)
                                {
                                    str.Clear();
                                    foreach (DataRow dr in lastDataTable.Rows)
                                    {
                                        str.Append("'" + dr[0] + "',");
                                    }
                                    result = casecausebLL.UpdateNodeType(str.Remove(str.Length - 1, 1).ToString(), 22);
                                }
                                //处理倒数二级节点
                                if (SecondDataTable != null && SecondDataTable.Rows.Count > 0)
                                {
                                    str.Clear();
                                    foreach (DataRow dr in SecondDataTable.Rows)
                                    {
                                        str.Append("'" + dr[0] + "',");
                                    }
                                    result = casecausebLL.UpdateNodeType(str.Remove(str.Length - 1, 1).ToString(), 17);
                                }
                                //处理倒数三级节点
                                if (ThirdDataTable != null && ThirdDataTable.Rows.Count > 0)
                                {
                                    str.Clear();
                                    foreach (DataRow dr in ThirdDataTable.Rows)
                                    {
                                        str.Append("'" + dr[0] + "',");
                                    }
                                    result = casecausebLL.UpdateNodeType(str.Remove(str.Length - 1, 1).ToString(), 16);
                                }
                                //处理倒数四级节点
                                if (FourDataTable != null && FourDataTable.Rows.Count > 0)
                                {
                                    str.Clear();
                                    foreach (DataRow dr in FourDataTable.Rows)
                                    {
                                        str.Append("'" + dr[0] + "',");
                                    }
                                    result = casecausebLL.UpdateNodeType(str.Remove(str.Length - 1, 1).ToString(), 15);
                                }
                                //处理其他剩余节点
                                if (OtherDataTable != null && OtherDataTable.Rows.Count > 0)
                                {
                                    str.Clear();
                                    foreach (DataRow dr in OtherDataTable.Rows)
                                    {
                                        str.Append("'" + dr[0] + "',");
                                    }
                                    result = casecausebLL.UpdateNodeType(str.Remove(str.Length - 1, 1).ToString(), 15);
                                }
                            }
                        }
                    }
                    #endregion
                    #region 修改二级节点类型
                    // 修改二级节点类型事件（诉请要素18 事实要素19 基本要素20）
                    //获取该节点下诉请要素下一级类型为“xml节点”的节点集合

                    DataTable appealTable = casecausebLL.GetElementData(cc_Id, "诉请要素");
                    if (appealTable != null && appealTable.Rows.Count > 0)
                    {
                        str.Clear();
                        foreach (DataRow res in appealTable.Rows)
                        {
                            str.Append("'" + res[0] + "',");
                        }

                        result = casecausebLL.UpdateNodeSubType(str.Remove(str.Length - 1, 1).ToString(), 18);
                    }
                    //获取该节点下事实要素下一级类型为“xml节点”的节点集合
                    DataTable TrueTable = casecausebLL.GetElementData(cc_Id, "事实要素");
                    if (TrueTable != null && TrueTable.Rows.Count > 0)
                    {
                        str.Clear();
                        foreach (DataRow res in TrueTable.Rows)
                        {
                            str.Append("'" + res[0] + "',");
                        }

                        result = casecausebLL.UpdateNodeSubType(str.Remove(str.Length - 1, 1).ToString(), 19);
                    }
                    //获取该节点下基本要素下一级类型为“xml节点”的节点集合
                    DataTable BaseTable = casecausebLL.GetElementData(cc_Id, "基本要素");
                    if (BaseTable != null && BaseTable.Rows.Count > 0)
                    {
                        str.Clear();
                        foreach (DataRow res in BaseTable.Rows)
                        {
                            str.Append("'" + res[0] + "',");
                        }

                        result = casecausebLL.UpdateNodeSubType(str.Remove(str.Length - 1, 1).ToString(), 20);
                    }
                    #endregion
                    if (result)
                    {
                        MsgBox.OK(" 批量修改成功！ ");
                    }
                    else if (ds.Tables[0].Rows.Count == 0 && appealTable.Rows.Count == 0 && TrueTable.Rows.Count == 0 && BaseTable.Rows.Count == 0)
                    {
                        MsgBox.Err(" 该节点下没有需要修改的节点类型！ ");
                    }
                    else
                    {
                        MsgBox.Err(" 批量修改失败！ ");
                    }
                }
                else
                {
                    MsgBox.Warn("选择节点案由不是民事案由，无法进行批量修改节点类型功能！");
                    return;
                }

            }
        }
        #endregion

        #region 在用户开始拖动项时发生
        /// <summary>
        /// 在用户开始拖动节点判断操作民事案由的权限
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tVCaseCause_ItemDrag(object sender, ItemDragEventArgs e)
        {
            if (clicknode.FullPath.Substring(0, 4) == "民事案由")
            {
                if (users.Contains(Gvar.uo.m_displayName))
                {
                    NewMethod1(e);
                }
                else
                {
                    MessageBox.Show("该用户没有操作民事案由的权限");
                    return;
                }
            }
            else if (clicknode.FullPath.Substring(0, 4) == "行政执法")
            {
                if (userXZs.Contains(Gvar.uo.m_displayName))
                {
                    NewMethod1(e);
                }
                else
                {
                    MessageBox.Show("该用户没有操作行政执法的权限");
                    return;
                }
            }
            else
            {
                NewMethod1(e);
            }
        }
        #endregion

        #region 开始拖动
        /// <summary>
        /// 开始拖动
        /// </summary>
        /// <param name="e"></param>
        private void NewMethod1(ItemDragEventArgs e)
        {
            //当前拖拽节点
            dragNode = (TreeNode)e.Item;
            //选中节点变为拖拽节点
            tVCaseCause.SelectedNode = dragNode;
            //记录当前拖拽节点的前景色
            dragNodeColor = dragNode.ForeColor;
            //前景色变为红色
            tVCaseCause.SelectedNode.ForeColor = Color.Green;

            this.imageListDrag.Images.Clear();
            //宽最大为256
            int width = this.dragNode.Bounds.Size.Width + tVCaseCause.Indent;
            if (width > 256) width = 256;
            this.imageListDrag.ImageSize = new Size(width, this.dragNode.Bounds.Height);

            //创建一个位图画布，当节点被拖动时存放节点的快照
            Bitmap bmp = new Bitmap(width, this.dragNode.Bounds.Height);
            //以bmp为画布创建制图工具
            Graphics gfx = Graphics.FromImage(bmp);
            //画出节点的快照位图
            gfx.DrawString(this.dragNode.Text, this.Font, new SolidBrush(Color.Red), (float)tVCaseCause.Indent, 1.0f);
            //将画好的位图保存
            this.imageListDrag.Images.Add(bmp);
            //获取当前鼠标在树上的位置
            Point p = this.PointToClient(Control.MousePosition);
            //计算鼠标位置与节点边界的位置       
            int dx = p.X + tVCaseCause.Indent - this.dragNode.Bounds.Left;
            //int dy = p.Y - this.dragNode.Bounds.Top;
            int dy = p.Y - this.dragNode.Bounds.Top - 150;
            //初始化节点快照的初始位置
            if (DragHelper.ImageList_BeginDrag(this.imageListDrag.Handle, 0, dx, dy))
            {
                //开始拖放操作
                this.DoDragDrop(bmp, DragDropEffects.Move);
                DragHelper.ImageList_EndDrag();
            }
        }
        #endregion

        #region 在用鼠标将某项拖动到控件的工作区时发生
        /// <summary>
        /// 在用鼠标将某项拖动到控件的工作区时发生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tVCaseCause_DragEnter(object sender, DragEventArgs e)
        {
            DragHelper.ImageList_DragEnter(tVCaseCause.Handle, e.X - tVCaseCause.Left,
              e.Y - tVCaseCause.Top);
            this.m_timer.Enabled = true;
        }
        #endregion

        #region 将对象拖出控件的边界区时发生
        /// <summary>
        /// 将对象拖出控件的边界区时发生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tVCaseCause_DragLeave(object sender, EventArgs e)
        {
            DragHelper.ImageList_DragLeave(tVCaseCause.Handle);
            this.m_timer.Enabled = false;
        }
        #endregion

        #region 将对象拖过控件的边界区时发生
        /// <summary>
        /// 将对象拖过控件的边界区时发生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tVCaseCause_DragOver(object sender, DragEventArgs e)
        {
            Point formP = tVCaseCause.PointToClient(new Point(e.X, e.Y));
            DragHelper.ImageList_DragMove(formP.X - tVCaseCause.Left, formP.Y - tVCaseCause.Top + 5);
            // Get actual drop node
            //获取当前的节点根据坐标位置
            TreeNode dropNode = tVCaseCause.GetNodeAt(tVCaseCause.PointToClient(new Point(e.X, e.Y)));
            //移动到节点树之外区域            
            //if (dropNode == null)
            //{

            //}
            //父级节点id 是否是同一级节点
            // m_isValid = dragNode.Name == dropNode.Name;
            if (dropNode != null && dragNode != dropNode)
            {
                if (casecausebLL.IsParentRealation(dragNode.Tag.ToString(), dropNode.Tag.ToString()))
                {
                    m_isValid = false;
                    e.Effect = DragDropEffects.None;
                    return;
                }
                else
                {
                    m_isValid = true;
                }
            }
            else
            {
                //变为不可操作
                e.Effect = DragDropEffects.None;
                return;
            }



            //变为可操作移动
            e.Effect = DragDropEffects.Move;

            // if mouse is on a new node select it
            //路过的节点不是当前节点
            if (this.tempDropNode != dropNode)
            {
                DragHelper.ImageList_DragShowNolock(false);
                //选中路过节点
                tVCaseCause.SelectedNode = dropNode;
                DragHelper.ImageList_DragShowNolock(true);
                tempDropNode = dropNode;
            }
            //TreeNode tmpNode = dropNode;
            //while (tmpNode.Parent != null)
            //{
            //    // if (tmpNode.Parent == this.m_dragNode) e.Effect = DragDropEffects.None;
            //    //拖拽节点和路过节点的父节点相等
            //    if (tmpNode.Parent == this.dragNode)
            //    { e.Effect = DragDropEffects.Move; }
            //    tmpNode = tmpNode.Parent;
            //}
        }
        #endregion

        #region 定时器控制树的滚动条
        /// <summary>
        /// 定时器控制树的滚动条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer_Tick(object sender, EventArgs e)
        {
            Point pt = tVCaseCause.PointToClient(Control.MousePosition);
            TreeNode node = tVCaseCause.GetNodeAt(pt);

            if (node == null) return;

            // 鼠标移动到树顶部时，如果有滚动条，滚动条上滚
            if (pt.Y < 30)
            {
                if (node.PrevVisibleNode != null)
                {
                    node = node.PrevVisibleNode;

                    DragHelper.ImageList_DragShowNolock(false);

                    node.EnsureVisible();
                    this.Refresh();

                    DragHelper.ImageList_DragShowNolock(true);
                }
            }
            // 鼠标移动到树底部时，如果有树有滚动条，滚动条下滚
            else if (pt.Y > tVCaseCause.Size.Height - 30)
            {
                if (node.NextVisibleNode != null)
                {
                    node = node.NextVisibleNode;

                    DragHelper.ImageList_DragShowNolock(false);
                    node.EnsureVisible();
                    this.Refresh();
                    DragHelper.ImageList_DragShowNolock(true);
                }
            }
        }
        #endregion

        #region 在用鼠标拖动某项时发生,在执行拖动期间发生
        /// <summary>
        /// 在用鼠标拖动某项时发生,在执行拖动期间发生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tVCaseCause_GiveFeedback(object sender, GiveFeedbackEventArgs e)
        {
            if (e.Effect == DragDropEffects.Move)
            {
                //不使用默认指针
                e.UseDefaultCursors = false;
                //是否是同一个父节点 是显示箭头光标否则无效光标
                if (m_isValid)
                {
                    this.Cursor = Cursors.Default;
                }
                else
                {
                    this.Cursor = Cursors.No;
                }
            }//使用默认指针
            else e.UseDefaultCursors = true;
        }
        #endregion

        #region 拖放操作完成时发生
        /// <summary>
        /// 拖放操作完成时发生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tVCaseCause_DragDrop(object sender, DragEventArgs e)
        {
            DragHelper.ImageList_DragLeave(tVCaseCause.Handle);
            //默认为箭头光标
            this.Cursor = Cursors.Default;
            //被拖拽节点前景色变为之前保存的颜色
            // dragNode.ForeColor = dragNodeColor;
            // Get drop node
            //当前节点
            TreeNode dropNode = tVCaseCause.GetNodeAt(tVCaseCause.PointToClient(new Point(e.X, e.Y)));
            dropNodeColor = dropNode.ForeColor;
            dragNode.ForeColor = dropNode.ForeColor = Color.Red;
            //自定义事件
            //9.4日新需求
            if (dragNode.Text.Equals(dropNode.Text))
            {
                MsgBox.Warn("与拖动目标名称相同时，无法移动");
                return;
            }

            // if(dragNode.Text)

            //被拖拽节点和当前节点不是一个节点并且目标节点不为空，目标节点不是被拖拽节点的子节点
            if (dropNode != null && dropNode.Parent != dragNode && dragNode != dropNode)
            {
                SYS_CaseCause sourceNode = casecausebLL.GetCaseCauseByCCID(dragNode.Tag.ToString());
                SYS_CaseCause targetNode = casecausebLL.GetCaseCauseByCCID(dropNode.Tag.ToString());
                MoveState ms = new MoveState(dragNode.Text, dropNode.Text);
                //拖拽节点的类型是案由类型并且目标节点的类型是案由类型则不能移动到下级
                //if (sourceNode.CC_NodeType == 2 && targetNode.CC_NodeType == 2)
                //{
                //    ms.LevelShow = true;
                //}
                //qc93:在同一节点下，子级拖动到父级，提示框的下级按钮变灰显示
                if (sourceNode.CC_ParentID == targetNode.CC_ID)
                {
                    ms.LevelShow = true;
                }


                //移动到上方、下方、下级
                ms.ShowDialog();
                if (ms.DialogResult == DialogResult.Yes)
                {
                    #region 不能拖动节点的情况
                    if (dropNode.Parent == null && (ms.moveNodeState == "上方" || ms.moveNodeState == "下方"))
                    {
                        MsgBox.Warn("不能拖动到根节点的上方或者下方!");
                        return;
                    }
                    if (targetNode.CC_NodeType == 12 && targetNode.CC_Name != "属性" && ms.moveNodeState == "下级")
                    {
                        MsgBox.Warn("任何节点不能移动到XML属性(除“属性”节点)的下级");
                        return;
                    }
                    if ((ms.moveNodeState == "上方" || ms.moveNodeState == "下方") && dropNode.Parent.Text != dragNode.Parent.Text)
                    {
                        List<string> obj = casecausebLL.GetTongJiNodes(dropNode.Parent.Tag.ToString());
                        if (obj.Contains(dragNode.Text))
                        {
                            MsgBox.Warn("拖动后同级有同名节点，无法移动");
                            return;
                        }
                    }
                    if (ms.moveNodeState == "下级")
                    {
                        List<string> obj = casecausebLL.GetTongJiNodes(dropNode.Tag.ToString());
                        if (obj.Contains(dragNode.Text))
                        {
                            MsgBox.Warn("拖动后同级有同名节点，无法移动");
                            return;
                        }
                    }
                    if (ms.moveNodeState != "下级")
                    {
                        //目标节点是xml属性并且目标节点的父节点是属性
                        if (targetNode.CC_NodeType == 12 && dropNode.Parent.Text == "属性" && targetNode.CC_Name != "属性")
                        {
                            //目标节点是xml属性
                            if (sourceNode.CC_NodeType != 12)
                            {
                                MsgBox.Warn("只有xml属性才能移动到Xml属性（除“属性”节点）的同级");
                                return;
                            }
                        }
                    }
                    if (ms.moveNodeState == "下级" && int.Parse(dragNode.Name) == 12 && dragNode.Nodes.Count > 0 && targetNode.CC_Name == "属性")
                    {
                        MsgBox.Warn("属性节点下只能有XML属性一层节点");
                        return;
                    }
                    if (ms.moveNodeState == "下级" && dropNode.Text == "属性")
                    {
                        if (sourceNode.CC_NodeType != 12)
                        {
                            MsgBox.Warn("属性节点下只能是XML属性节点");
                            return;
                        }
                    }
                    if (sourceNode.CC_Name == "属性" && dropNode.Parent.Text == "属性")
                    {
                        MsgBox.Warn("拖动的属性节点不允许拖动到属性节点的下级");
                        return;
                    }
                    #endregion

                    //不需要修改数据库的
                    if ((ms.moveNodeState == "上方" && dragNode.NextNode == dropNode) || (ms.moveNodeState == "下方" && dropNode.NextNode == dragNode) || (ms.moveNodeState == "下级" && sourceNode.CC_ParentID == targetNode.CC_ID))
                    {
                        tVCaseCause.SelectedNode = dragNode;

                        return;
                    }
                    if (dropNode.Text == dragNode.Text && (ms.moveNodeState == "上方" || ms.moveNodeState == "下方"))
                    {
                        if (MessageBox.Show("是否将" + dropNode.Text + "移动到" + dropNode.Text + "的" + ms.moveNodeState + "?", "提示", MessageBoxButtons.YesNo) == DialogResult.No)
                            return;
                    }
                    if (ms.moveNodeState == "下级" && !string.IsNullOrEmpty(casecausebLL.Exists(dragNode.Text, dropNode.Tag.ToString())))
                    {
                        if (MessageBox.Show("是否将" + dragNode.Text + "移动到" + dragNode.Text + "的" + ms.moveNodeState + "?", "提示", MessageBoxButtons.YesNo) == DialogResult.No)
                            return;
                    }
                    OperLogDAL.AddOperLog(PublicMethod.UserName, "拖动节点", "将节点" + dragNode.Text + "移动到节点" + dropNode.Text + ms.moveNodeState, "");
                    string[] str = dragNode.FullPath.Split('\\');
                    //原节点的上一级节点
                    string dragNodeUpLevel = str[str.Length - 2];


                    //对属性进行单独处理
                    if (sourceNode.CC_NodeType == 12)
                    {
                        //来源节点XML
                        SYS_CaseCause caseCausexml = casecausebLL.IsParentRealation1(sourceNode.CC_ID);
                        caseCausexml.ElementXML = Getxml("SYS_CaseCause\\ElementXML", caseCausexml.CC_ID);
                        //目标节点xml
                        SYS_CaseCause caseTargetCausexml = casecausebLL.IsParentRealation1(targetNode.CC_ID);
                        caseTargetCausexml.ElementXML = Getxml("SYS_CaseCause\\ElementXML", caseTargetCausexml.CC_ID);
                        XmlDocument doc = new XmlDocument();
                        XmlDocument doc1 = new XmlDocument();
                        XmlNode objxml = null;
                        XmlNode objParentXml = null;
                        XmlNode objxml1 = null;
                        XmlNode objParentXml1 = null;
                        if (ms.moveNodeState == "上方" || ms.moveNodeState == "下方")
                        {

                            if (sourceNode.CC_ParentID == targetNode.CC_ParentID)
                            {
                                if (casecausebLL.UpdateItemSort(sourceNode, targetNode, ms.moveNodeState))
                                {
                                    double sourceSort = sourceNode.CC_SerialNumb;
                                    double targetSort = targetNode.CC_SerialNumb;
                                    switch (ms.moveNodeState)
                                    {
                                        case "上方":
                                            dragNode.Parent.Nodes.Remove(dragNode);
                                            //if (sourceSort < targetSort)
                                            //{
                                            dropNode.Parent.Nodes.Insert(dropNode.Index, dragNode);
                                            //}else
                                            //{
                                            //    dropNode.Parent.Nodes.Insert(dropNode.Index)
                                            //}
                                            break;
                                        case "下方":
                                            dragNode.Parent.Nodes.Remove(dragNode);
                                            dropNode.Parent.Nodes.Insert(dropNode.Index + 1, dragNode);
                                            break;
                                        case "下级":
                                            dragNode.Parent.Nodes.Remove(dragNode);
                                            dropNode.Nodes.Add(dragNode);
                                            break;
                                    }
                                    return;
                                }
                            }

                            //如果来源节点是属性并且目标节点不等于属性时
                            if (sourceNode.CC_NodeType == 12 && sourceNode.CC_Name != "属性")
                            {
                                #region 修改节点树结构和数据库
                                SYS_CaseCause nowNode = null;
                                //目标节点父节点xml
                                SYS_CaseCause caseNode = casecausebLL.GetCaseCauseByCCID(dragNode.Tag.ToString());
                                SYS_CaseCause caseTargetNode = casecausebLL.GetCaseCauseByCCID(dropNode.Parent.Tag.ToString());
                                var model = new SYS_CaseCause();
                                string sourceNodeAllParent = sourceNode.AllParentName;
                                //判断有没有属性节点
                                //获取属性节点
                                //   if (MessageBox.Show("是否将" + dropNode.Text + "移动到" + dropNode.Text + "的" + ms.moveNodeState + "?", "提示", MessageBoxButtons.YesNo) == DialogResult.No)
                                if (targetNode.CC_Name == "属性")
                                {
                                    DialogResult = MessageBox.Show("是否修改" + sourceNode.CC_Name + "的类型为XML节点", "提示", MessageBoxButtons.YesNoCancel);
                                    //修改节点类型为XML节点
                                    if (DialogResult == DialogResult.Yes)
                                    {

                                        model = sourceNode;
                                        model.CC_ParentID = caseTargetNode.CC_ID.ToString();
                                        model.AllParentId = caseTargetNode.AllParentId + "," + sourceNode.CC_ID;
                                        model.AllParentName = caseTargetNode.AllParentName + "," + sourceNode.CC_Name;
                                        model.HW_level = model.AllParentName.Split(',').Length;
                                        model.CC_NodeType = 11;
                                        model.CC_SerialNumb = casecausebLL.GetNodeChildSerialNumber(caseTargetNode.CC_ID.ToString());
                                        string name = "";
                                        //if (model.CC_NodeType == 12 || model.CC_NodeType == 11)
                                        //{
                                        if (!string.IsNullOrEmpty(caseTargetCausexml.ElementXML))
                                        {
                                            //if (model.CC_Name == "属性")
                                            //{
                                            string str1 = model.AllParentName.ToString();
                                            int i;
                                            if (str1.Contains("案由要素"))
                                            {
                                                i = str1.IndexOf("案由要素");
                                            }
                                            else
                                            {
                                                i = str1.IndexOf(caseCausexml.CC_Name);
                                            }
                                            string str2 = string.Empty;
                                            if (model.CC_Name == "属性")
                                            {
                                                str2 = str1.Substring(i - 1).Replace(',', '/').Replace("/属性", "");
                                            }
                                            else
                                            {
                                                str2 = str1.Substring(i - 1).Replace(',', '/').Replace("/属性/", "/@");
                                            }
                                            model.XmlPath = str2;
                                            //}
                                        }
                                        //   }
                                        if (casecausebLL.UpdateSYS_CaseCause(model, Gvar.uo.m_displayName))
                                        {
                                            var addnode = new TreeNode();
                                            addnode.Tag = model.CC_ID;
                                            addnode.Text = model.CC_Name;
                                            addnode.Name = model.CC_NodeType.ToString();
                                            if (ms.moveNodeState == "上方")
                                            {
                                                dropNode.Parent.Nodes.Insert(dropNode.Index, addnode);
                                            }
                                            else if (ms.moveNodeState == "下方")
                                            {
                                                dropNode.Parent.Nodes.Insert(dropNode.Index + 1, addnode);
                                            }
                                            dropNode.Parent.Expand();
                                            tVCaseCause.SelectedNode = addnode;
                                            dragNode.Parent.Nodes.Remove(dragNode);
                                            #region 修改xml结构
                                            if (!string.IsNullOrEmpty(caseCausexml.ElementXML))
                                            {
                                                string xml = caseCausexml.ElementXML.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @"");
                                                doc.LoadXml(xml);
                                                string res2 = string.Empty;
                                                if (sourceNodeAllParent.Contains(",属性"))
                                                {
                                                    int res01 = sourceNodeAllParent.LastIndexOf(",属性");
                                                    res2 = sourceNodeAllParent.Substring(0, res01);
                                                }
                                                else
                                                {
                                                    res2 = sourceNodeAllParent;
                                                }
                                                res2 = res2.Replace("," + sourceNode.CC_Name, "");
                                                int i = 0;
                                                string ayysId = casecausebLL.GetAyysIDByName(caseCausexml.CC_ID);
                                                if (!string.IsNullOrEmpty(ayysId) && res2.Contains("案由要素"))
                                                {
                                                    i = res2.LastIndexOf("案由要素");
                                                }
                                                else
                                                {
                                                    i = res2.LastIndexOf(caseCausexml.CC_Name);
                                                }
                                                //int i = res2.LastIndexOf(caseCausexml.CC_Name);
                                                string xmlPath = res2.Substring(i);
                                                string[] strs = xmlPath.Split(',');
                                                StringBuilder sb = new StringBuilder();
                                                foreach (var item in strs)
                                                {
                                                    sb.Append("/" + item);
                                                }
                                                //原节点路由
                                                string res1 = sb.ToString();
                                                if (!string.IsNullOrEmpty(res1))
                                                {
                                                    objxml = doc.SelectSingleNode(res1);
                                                    if (objxml != null)
                                                    {
                                                        XmlElement objxml001 = (XmlElement)objxml;
                                                        objxml001.RemoveAttribute(sourceNode.CC_Name);
                                                    }
                                                }
                                            }
                                            bool b = false;
                                            if (!string.IsNullOrEmpty(caseTargetCausexml.ElementXML))
                                            {
                                                if (caseCausexml.CC_ID == caseTargetCausexml.CC_ID)
                                                {
                                                    doc1 = doc;
                                                    b = true;
                                                }
                                                else
                                                {
                                                    string xml = caseTargetCausexml.ElementXML.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @"");
                                                    doc1.LoadXml(xml);
                                                }
                                                int i = targetNode.AllParentName.LastIndexOf(caseTargetCausexml.CC_Name);
                                                string xmlPath = targetNode.AllParentName.Substring(i);
                                                i = xmlPath.LastIndexOf(dropNode.Text);
                                                xmlPath = xmlPath.Substring(0, i - 1);
                                                xmlPath = xmlPath.Replace(",属性", "");

                                                string[] strs = xmlPath.Split(',');
                                                StringBuilder sb = new StringBuilder();
                                                foreach (var item in strs)
                                                {
                                                    sb.Append("/" + item);
                                                }
                                                //目标节点路由
                                                string res2 = sb.ToString();


                                                //int j1 = targetNode.AllParentName.LastIndexOf(caseTargetCausexml.CC_Name);
                                                //string xmlPath1 = targetNode.AllParentName.Substring(j1);
                                                //string[] strs1 = xmlPath1.Split(',');
                                                //StringBuilder sb1 = new StringBuilder();
                                                //foreach (var item in strs1)
                                                //{
                                                //    sb1.Append("/" + item);
                                                //}


                                                ////目标节点路由
                                                //string res20 = sb1.ToString();

                                                if (!string.IsNullOrEmpty(res2))
                                                {
                                                    objxml1 = doc1.SelectSingleNode(res2);
                                                    //XmlNode objxml2 = doc1.SelectSingleNode(res20);
                                                    if (objxml1 != null)
                                                    {
                                                        // XmlElement objxml001 = (XmlElement)objxml1;
                                                        XmlElement objElement = doc1.CreateElement(sourceNode.CC_Name);
                                                        objxml1.AppendChild(objElement);
                                                    }

                                                }
                                            }
                                            if (b)
                                            {
                                                if (!string.IsNullOrEmpty(doc1.InnerXml.ToString()))
                                                {
                                                    string res3 = FormatXML(doc1.InnerXml.ToString());
                                                    bool res = casecausebLL.UpdateElementXML(caseCausexml.CC_ID, res3);
                                                }
                                            }
                                            else
                                            {
                                                if (!string.IsNullOrEmpty(doc.InnerXml.ToString()))
                                                {
                                                    string res3 = FormatXML(doc.InnerXml.ToString());
                                                    bool res = casecausebLL.UpdateElementXML(caseCausexml.CC_ID, res3);
                                                }

                                                if (!string.IsNullOrEmpty(doc1.InnerXml.ToString()))
                                                {
                                                    string res3 = FormatXML(doc1.InnerXml.ToString());
                                                    bool res = casecausebLL.UpdateElementXML(caseTargetCausexml.CC_ID, res3);
                                                }
                                            }
                                            #endregion
                                        }
                                    }

                                    //添加到属性的下级
                                    else if (DialogResult == DialogResult.No)
                                    {
                                        string objProperty = casecausebLL.IsHaveProperty(dropNode.Parent.Tag.ToString());
                                        if (string.IsNullOrEmpty(objProperty) && dropNode.Parent.Text != "属性")
                                        {

                                            //创建属性节点
                                            model.CC_ID = newid.JudgeDoc_CreateID("SYS_CaseCause");
                                            model.CC_Name = "属性";
                                            model.CC_ParentID = dropNode.Parent.Tag.ToString();
                                            model.CC_NodeType = 12;
                                            model.AllParentId = caseTargetNode.AllParentId + "," + model.CC_ID;
                                            model.AllParentName = caseTargetNode.AllParentName + "," + model.CC_Name;
                                            model.HW_level = model.AllParentName.Split(',').Length;
                                            model.CC_SerialNumb = 1;
                                            casecausebLL.AddPropertyUpdateSerialNum(model.CC_ParentID);

                                            //if (model.CC_NodeType == 12 || model.CC_NodeType == 11)
                                            //{
                                            if (!string.IsNullOrEmpty(caseTargetCausexml.ElementXML))
                                            {
                                                //if (model.CC_Name == "属性")
                                                //{
                                                string str3 = model.AllParentName.ToString();
                                                int i;
                                                if (str3.Contains("案由要素"))
                                                {
                                                    i = str3.IndexOf("案由要素");
                                                }
                                                else
                                                {
                                                    i = str3.IndexOf(caseCausexml.CC_Name);
                                                }
                                                string str4 = string.Empty;
                                                if (model.CC_Name == "属性")
                                                {
                                                    str4 = str3.Substring(i - 1).Replace(',', '/').Replace("/属性", "");
                                                }
                                                else
                                                {
                                                    str4 = str3.Substring(i - 1).Replace(',', '/').Replace("/属性/", "/@");
                                                }
                                                model.XmlPath = str4;
                                                //}
                                            }
                                            // }

                                            if (casecausebLL.AddSYS_CaseCause(model, Gvar.uo.m_displayName))
                                            {
                                                //添加成功属性节点                                            
                                                var addnode = new TreeNode();
                                                addnode.Tag = model.CC_ID;
                                                addnode.Text = model.CC_Name;
                                                addnode.Name = model.CC_NodeType.ToString();
                                                dropNode.Parent.Nodes.Insert(0, addnode);
                                                dropNode.Parent.Expand();
                                                // editnode = clicknode = addnode; 
                                                nowNode = casecausebLL.GetCaseCauseByCCID(model.CC_ID.ToString());
                                                model = new SYS_CaseCause();

                                            }
                                        }
                                        else
                                        {
                                            if (dropNode.Parent.Text == "属性")
                                            {
                                                nowNode = casecausebLL.GetCaseCauseByCCID(dropNode.Parent.Tag.ToString());
                                            }
                                            else
                                            {
                                                nowNode = casecausebLL.GetCaseCauseByCCID(objProperty);
                                            }
                                        }
                                        //如果当前xml属性是目标节点属性下的无需修改
                                        if (caseNode.CC_ParentID == nowNode.CC_ID)
                                        {
                                            return;
                                        }
                                        model = caseNode;
                                        //赋值来源节点的内容                     
                                        model.CC_ParentID = nowNode.CC_ID.ToString();
                                        model.AllParentId = nowNode.AllParentId + "," + caseNode.CC_ID;
                                        model.AllParentName = nowNode.AllParentName + "," + caseNode.CC_Name;
                                        model.HW_level = model.AllParentName.Split(',').Length;
                                        model.CC_SerialNumb = casecausebLL.GetNodeChildSerialNumber(nowNode.CC_ID.ToString());

                                        //if (model.CC_NodeType == 12 || model.CC_NodeType == 11)
                                        //{
                                        if (!string.IsNullOrEmpty(caseTargetCausexml.ElementXML))
                                        {
                                            //if (model.CC_Name == "属性")
                                            //{
                                            string str1 = model.AllParentName.ToString();
                                            int i;
                                            if (str1.Contains("案由要素"))
                                            {
                                                i = str1.IndexOf("案由要素");
                                            }
                                            else
                                            {
                                                i = str1.IndexOf(caseCausexml.CC_Name);
                                            }
                                            string str2 = string.Empty;
                                            if (model.CC_Name == "属性")
                                            {
                                                str2 = str1.Substring(i - 1).Replace(',', '/').Replace("/属性", "");
                                            }
                                            else
                                            {
                                                str2 = str1.Substring(i - 1).Replace(',', '/').Replace("/属性/", "/@");
                                            }
                                            model.XmlPath = str2;
                                            //}
                                        }
                                        //}

                                        if (casecausebLL.UpdateSYS_CaseCause(model, Gvar.uo.m_displayName))
                                        {
                                            // casecausebLL.CaseCauseUpdateAllPid(model.CC_ID);
                                            //   editnode.Expand();
                                            var addnode = new TreeNode();
                                            addnode.Tag = model.CC_ID;
                                            addnode.Text = model.CC_Name;
                                            addnode.Name = model.CC_NodeType.ToString();
                                            if (dropNode.Parent.Text == "属性")
                                            {
                                                dropNode.Parent.Nodes.Insert(0, addnode);
                                                dropNode.Parent.Expand();
                                            }
                                            else
                                            {
                                                TreeNode attbuteNode = null;
                                                foreach (TreeNode r in dropNode.Parent.Nodes)
                                                {
                                                    if (r.Text == "属性")
                                                    {
                                                        attbuteNode = r;
                                                        break;
                                                    }
                                                }
                                                attbuteNode.Nodes.Add(addnode);
                                                attbuteNode.Expand();
                                                //dropNode.Parent.FirstNode.Nodes.Insert(0, addnode);
                                                //dropNode.Parent.FirstNode.Expand();
                                            }
                                            tVCaseCause.SelectedNode = addnode;

                                        }
                                        #endregion
                                        dragNode.Parent.Nodes.Remove(dragNode);
                                        #region 修改xml结构
                                        if (!string.IsNullOrEmpty(caseCausexml.ElementXML))
                                        {
                                            string xml = caseCausexml.ElementXML.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @"");
                                            doc.LoadXml(xml);
                                            string res2 = string.Empty;
                                            if (sourceNode.AllParentName.Contains(",属性"))
                                            {
                                                int res01 = sourceNode.AllParentName.LastIndexOf(",属性");
                                                res2 = sourceNode.AllParentName.Substring(0, res01);
                                            }
                                            else
                                            {
                                                res2 = sourceNode.AllParentName;
                                            }
                                            int i = 0;
                                            string ayysId = casecausebLL.GetAyysIDByName(caseCausexml.CC_ID);
                                            if (!string.IsNullOrEmpty(ayysId) && res2.Contains("案由要素"))
                                            {
                                                i = res2.LastIndexOf("案由要素");
                                            }
                                            else
                                            {
                                                i = res2.LastIndexOf(caseCausexml.CC_Name);
                                            }
                                            //int i = res2.LastIndexOf(caseCausexml.CC_Name);
                                            string xmlPath = res2.Substring(i);
                                            string[] strs = xmlPath.Split(',');
                                            StringBuilder sb = new StringBuilder();
                                            foreach (var item in strs)
                                            {
                                                sb.Append("/" + item);
                                            }
                                            //原节点路由
                                            string res1 = sb.ToString();
                                            if (!string.IsNullOrEmpty(res1))
                                            {
                                                objxml = doc.SelectSingleNode(res1);
                                                if (objxml != null)
                                                {
                                                    XmlElement objxml001 = (XmlElement)objxml;
                                                    objxml001.RemoveAttribute(sourceNode.CC_Name);
                                                }
                                            }
                                        }
                                        bool b = false;
                                        if (!string.IsNullOrEmpty(caseTargetCausexml.ElementXML))
                                        {
                                            if (caseCausexml.CC_ID == caseTargetCausexml.CC_ID)
                                            {
                                                doc1 = doc;
                                                b = true;
                                            }
                                            else
                                            {
                                                string xml = caseTargetCausexml.ElementXML.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @"");
                                                doc1.LoadXml(xml);
                                            }
                                            int i = targetNode.AllParentName.LastIndexOf(caseTargetCausexml.CC_Name);
                                            string xmlPath = targetNode.AllParentName.Substring(i);
                                            i = xmlPath.LastIndexOf(dropNode.Text);
                                            xmlPath = xmlPath.Substring(0, i - 1);
                                            xmlPath = xmlPath.Replace(",属性", "");
                                            string[] strs = xmlPath.Split(',');
                                            StringBuilder sb = new StringBuilder();
                                            foreach (var item in strs)
                                            {
                                                sb.Append("/" + item);
                                            }
                                            //目标节点路由
                                            string res2 = sb.ToString();
                                            if (!string.IsNullOrEmpty(res2))
                                            {
                                                objxml1 = doc1.SelectSingleNode(res2);
                                                if (objxml1 != null)
                                                {
                                                    XmlElement objxml001 = (XmlElement)objxml1;
                                                    objxml001.SetAttribute(sourceNode.CC_Name, "");
                                                }

                                            }
                                        }
                                        if (b)
                                        {
                                            if (!string.IsNullOrEmpty(doc1.InnerXml.ToString()))
                                            {
                                                string res3 = FormatXML(doc1.InnerXml.ToString());
                                                bool res = casecausebLL.UpdateElementXML(caseCausexml.CC_ID, res3);
                                            }
                                        }
                                        else
                                        {
                                            if (!string.IsNullOrEmpty(doc.InnerXml.ToString()))
                                            {
                                                string res3 = FormatXML(doc.InnerXml.ToString());
                                                bool res = casecausebLL.UpdateElementXML(caseCausexml.CC_ID, res3);
                                            }

                                            if (!string.IsNullOrEmpty(doc1.InnerXml.ToString()))
                                            {
                                                string res3 = FormatXML(doc1.InnerXml.ToString());
                                                bool res = casecausebLL.UpdateElementXML(caseTargetCausexml.CC_ID, res3);
                                            }
                                        }
                                        #endregion
                                    }
                                    else if (DialogResult == DialogResult.Cancel)
                                    {
                                        return;
                                    }
                                }
                                else
                                {
                                    string objProperty = casecausebLL.IsHaveProperty(dropNode.Parent.Tag.ToString());
                                    if (string.IsNullOrEmpty(objProperty) && dropNode.Parent.Text != "属性")
                                    {

                                        //创建属性节点
                                        model.CC_ID = newid.JudgeDoc_CreateID("SYS_CaseCause");
                                        model.CC_Name = "属性";
                                        model.CC_ParentID = dropNode.Parent.Tag.ToString();
                                        model.CC_NodeType = 12;
                                        model.AllParentId = caseTargetNode.AllParentId + "," + model.CC_ID;
                                        model.AllParentName = caseTargetNode.AllParentName + "," + model.CC_Name;
                                        model.HW_level = model.AllParentName.Split(',').Length;
                                        model.CC_SerialNumb = 1;
                                        casecausebLL.AddPropertyUpdateSerialNum(model.CC_ParentID);

                                        //if (model.CC_NodeType == 12 || model.CC_NodeType == 11)
                                        //{
                                        if (!string.IsNullOrEmpty(caseTargetCausexml.ElementXML))
                                        {
                                            //if (model.CC_Name == "属性")
                                            //{
                                            int i;
                                            if (model.AllParentName.Contains("案由要素"))
                                            {
                                                i = model.AllParentName.IndexOf("案由要素");
                                            }
                                            else
                                            {
                                                i = model.AllParentName.IndexOf(caseCausexml.CC_Name);
                                            }
                                            //int i = model.AllParentName.ToString().IndexOf(caseCausexml.CC_Name);
                                            string str5 = string.Empty;
                                            if (model.CC_Name == "属性")
                                            {
                                                str5 = model.AllParentName.ToString().Substring(i - 1).Replace(',', '/').Replace("/属性", "");
                                            }
                                            else
                                            {
                                                str5 = model.AllParentName.ToString().Substring(i - 1).Replace(',', '/').Replace("/属性/", "/@");
                                            }
                                            model.XmlPath = str5;
                                            //}
                                        }
                                        // }

                                        if (casecausebLL.AddSYS_CaseCause(model, Gvar.uo.m_displayName))
                                        {
                                            //添加成功属性节点
                                            // casecausebLL.CaseCauseUpdateAllPid(model.CC_ID);
                                            var addnode = new TreeNode();
                                            addnode.Tag = model.CC_ID;
                                            addnode.Text = model.CC_Name;
                                            addnode.Name = model.CC_NodeType.ToString();
                                            dropNode.Parent.Nodes.Insert(0, addnode);
                                            dropNode.Parent.Expand();
                                            // editnode = clicknode = addnode; 
                                            nowNode = casecausebLL.GetCaseCauseByCCID(model.CC_ID.ToString());
                                            model = new SYS_CaseCause();

                                        }
                                    }
                                    else
                                    {
                                        if (dropNode.Parent.Text == "属性")
                                        {
                                            nowNode = casecausebLL.GetCaseCauseByCCID(dropNode.Parent.Tag.ToString());
                                        }
                                        else
                                        {
                                            nowNode = casecausebLL.GetCaseCauseByCCID(objProperty);
                                        }
                                    }
                                    //如果当前xml属性是目标节点属性下的无需修改
                                    if (caseNode.CC_ParentID == nowNode.CC_ID)
                                    {
                                        return;
                                    }
                                    model = caseNode;
                                    //赋值来源节点的内容                     
                                    model.CC_ParentID = nowNode.CC_ID.ToString();
                                    model.AllParentId = nowNode.AllParentId + "," + caseNode.CC_ID;
                                    model.AllParentName = nowNode.AllParentName + "," + caseNode.CC_Name;
                                    model.HW_level = model.AllParentName.Split(',').Length;
                                    model.CC_SerialNumb = casecausebLL.GetNodeChildSerialNumber(nowNode.CC_ID.ToString());

                                    //if (model.CC_NodeType == 12 || model.CC_NodeType == 11)
                                    //{
                                    if (!string.IsNullOrEmpty(caseTargetCausexml.ElementXML))
                                    {
                                        //if (model.CC_Name == "属性")
                                        //{
                                        int i;
                                        if (model.AllParentName.Contains("案由要素"))
                                        {
                                            i = model.AllParentName.IndexOf("案由要素");
                                        }
                                        else
                                        {
                                            i = model.AllParentName.IndexOf(caseCausexml.CC_Name);
                                        }
                                        //int i = model.AllParentName.ToString().IndexOf(caseCausexml.CC_Name);
                                        string str5 = string.Empty;
                                        if (model.CC_Name == "属性")
                                        {
                                            str5 = model.AllParentName.ToString().Substring(i - 1).Replace(',', '/').Replace("/属性", "");
                                        }
                                        else
                                        {
                                            str5 = model.AllParentName.ToString().Substring(i - 1).Replace(',', '/').Replace("/属性/", "/@");
                                        }
                                        model.XmlPath = str5;
                                        //}
                                    }
                                    //   }

                                    if (casecausebLL.UpdateSYS_CaseCause(model, Gvar.uo.m_displayName))
                                    {
                                        //casecausebLL.CaseCauseUpdateAllPid(model.CC_ID);
                                        //   editnode.Expand();
                                        var addnode = new TreeNode();
                                        addnode.Tag = model.CC_ID;
                                        addnode.Text = model.CC_Name;
                                        addnode.Name = model.CC_NodeType.ToString();
                                        if (dropNode.Parent.Text == "属性")
                                        {
                                            //  dropNode.Parent.Nodes.Insert(dropNode.Index, dragNode);
                                            if (ms.moveNodeState == "上方")
                                            {
                                                dropNode.Parent.Nodes.Insert(dropNode.Index, addnode);
                                            }
                                            else if (ms.moveNodeState == "下方")
                                            {
                                                dropNode.Parent.Nodes.Insert(dropNode.Index + 1, addnode);
                                            }
                                            // dropNode.Parent.Nodes.Insert(0, addnode);
                                            dropNode.Parent.Expand();
                                        }
                                        else
                                        {
                                            TreeNode attbuteNode = null;
                                            TreeNodeCollection treeNodes = dropNode.Parent.Nodes;
                                            foreach (TreeNode r in dropNode.Parent.Nodes)
                                            {
                                                if (r.Text == "属性")
                                                {
                                                    attbuteNode = r;
                                                    break;
                                                }
                                            }
                                            attbuteNode.Nodes.Add(addnode);
                                            attbuteNode.Expand();
                                        }
                                        tVCaseCause.SelectedNode = addnode;

                                    }
                                    // dragNode.Parent.Nodes.Remove(dragNode);
                                    if (dragNode.Parent.Text == "属性" && dragNode.Parent.Nodes.Count == 1)
                                    {
                                        //删除属性节点
                                        if (casecausebLL.DeleteCaseCauseByCCId(dragNode.Parent.Tag.ToString()))
                                        {
                                            dragNode.Parent.Parent.Nodes.Remove(dragNode.Parent);
                                        }
                                    }
                                    else
                                    {
                                        dragNode.Parent.Nodes.Remove(dragNode);
                                    }
                                    #region 修改xml结构
                                    if (!string.IsNullOrEmpty(caseCausexml.ElementXML))
                                    {
                                        string xml = caseCausexml.ElementXML.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @"");
                                        doc.LoadXml(xml);
                                        string res2 = string.Empty;
                                        if (sourceNode.AllParentName.Contains(",属性"))
                                        {
                                            int res01 = sourceNode.AllParentName.LastIndexOf(",属性");
                                            res2 = sourceNode.AllParentName.Substring(0, res01);
                                        }
                                        else
                                        {
                                            res2 = sourceNode.AllParentName;
                                        }
                                        int i = 0;
                                        string ayysId = casecausebLL.GetAyysIDByName(caseCausexml.CC_ID);
                                        if (!string.IsNullOrEmpty(ayysId) && res2.Contains("案由要素"))
                                        {
                                            i = res2.LastIndexOf("案由要素");
                                        }
                                        else
                                        {
                                            i = res2.LastIndexOf(caseCausexml.CC_Name);
                                        }

                                        //int i = res2.LastIndexOf(caseCausexml.CC_Name);
                                        string xmlPath = res2.Substring(i);
                                        string[] strs = xmlPath.Split(',');
                                        StringBuilder sb = new StringBuilder();
                                        foreach (var item in strs)
                                        {
                                            sb.Append("/" + item);
                                        }
                                        //原节点路由
                                        string res1 = sb.ToString();
                                        if (!string.IsNullOrEmpty(res1))
                                        {
                                            objxml = doc.SelectSingleNode(res1);
                                            if (objxml != null)
                                            {
                                                XmlElement objxml001 = (XmlElement)objxml;
                                                objxml001.RemoveAttribute(sourceNode.CC_Name);
                                            }
                                        }
                                    }
                                    bool b = false;
                                    if (!string.IsNullOrEmpty(caseTargetCausexml.ElementXML))
                                    {
                                        if (caseCausexml.CC_ID == caseTargetCausexml.CC_ID)
                                        {
                                            doc1 = doc;
                                            b = true;
                                        }
                                        else
                                        {
                                            string xml = caseTargetCausexml.ElementXML.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @"");
                                            doc1.LoadXml(xml);
                                        }
                                        //int i = targetNode.AllParentName.LastIndexOf(caseTargetCausexml.CC_Name);
                                        //string xmlPath = targetNode.AllParentName.Substring(i);
                                        //i = xmlPath.LastIndexOf(dropNode.Text);
                                        //xmlPath = xmlPath.Substring(0, i - 1);
                                        //xmlPath = xmlPath.Replace(",属性", "");
                                        //string[] strs = xmlPath.Split(',');
                                        //StringBuilder sb = new StringBuilder();
                                        //foreach (var item in strs)
                                        //{
                                        //    sb.Append("/" + item);
                                        //}
                                        //目标节点路由
                                        string res2 = string.Empty;
                                        if (targetNode.XmlPath.Contains("/@"))
                                        {
                                            res2 = targetNode.XmlPath.Substring(0, targetNode.XmlPath.IndexOf("/@"));
                                        }
                                        else
                                        {
                                            res2 = targetNode.XmlPath;
                                        }
                                        if (!string.IsNullOrEmpty(res2))
                                        {
                                            objxml1 = doc1.SelectSingleNode(res2);
                                            if (objxml1 != null)
                                            {
                                                XmlElement objxml001 = (XmlElement)objxml1;
                                                objxml001.SetAttribute(sourceNode.CC_Name, "");
                                            }

                                        }
                                    }
                                    if (b)
                                    {
                                        if (!string.IsNullOrEmpty(doc1.InnerXml.ToString()))
                                        {
                                            string res3 = FormatXML(doc1.InnerXml.ToString());
                                            bool res = casecausebLL.UpdateElementXML(caseCausexml.CC_ID, res3);
                                        }
                                    }
                                    else
                                    {
                                        if (!string.IsNullOrEmpty(doc.InnerXml.ToString()))
                                        {
                                            string res3 = FormatXML(doc.InnerXml.ToString());
                                            bool res = casecausebLL.UpdateElementXML(caseCausexml.CC_ID, res3);
                                        }

                                        if (!string.IsNullOrEmpty(doc1.InnerXml.ToString()))
                                        {
                                            string res3 = FormatXML(doc1.InnerXml.ToString());
                                            bool res = casecausebLL.UpdateElementXML(caseTargetCausexml.CC_ID, res3);
                                        }
                                    }
                                    #endregion
                                }
                            }
                            else if (sourceNode.CC_NodeType == 12 && sourceNode.CC_Name == "属性")
                            {
                                #region MyRegion
                                if (!string.IsNullOrEmpty(caseCausexml.ElementXML))
                                {
                                    string xml = caseCausexml.ElementXML.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @"");
                                    doc.LoadXml(xml);

                                    //int res01 = sourceNode.AllParentName.LastIndexOf(",属性");
                                    //string res2 = sourceNode.AllParentName.Substring(0, res01);
                                    //int i = res2.LastIndexOf(caseCausexml.CC_Name);
                                    //string xmlPath = res2.Substring(i);
                                    //string[] strs = xmlPath.Split(',');
                                    //StringBuilder sb = new StringBuilder();
                                    //foreach (var item in strs)
                                    //{
                                    //    sb.Append("/" + item);
                                    //}
                                    //原节点路由
                                    string res1 = sourceNode.XmlPath;
                                    if (!string.IsNullOrEmpty(res1))
                                    {
                                        objxml = doc.SelectSingleNode(res1);
                                        if (objxml != null)
                                        {
                                            XmlAttributeCollection xac = objxml.Attributes;
                                            if (xac.Count > 0)
                                            {
                                                sb1.Clear();
                                                foreach (XmlAttribute xa in xac)
                                                {
                                                    sb1.Append(xa.Name + ",");
                                                }
                                            }
                                            XmlElement objxml001 = (XmlElement)objxml;
                                            objxml001.RemoveAllAttributes();
                                        }
                                    }
                                }
                                bool b = false;

                                bool c = false;
                                if (!string.IsNullOrEmpty(caseTargetCausexml.ElementXML))
                                {
                                    if (caseCausexml.CC_ID == caseTargetCausexml.CC_ID)
                                    {
                                        doc1 = doc;
                                        b = true;
                                    }
                                    else
                                    {
                                        string xml = caseTargetCausexml.ElementXML.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @"");
                                        doc1.LoadXml(xml);
                                    }
                                    int i = targetNode.AllParentName.LastIndexOf(caseTargetCausexml.CC_Name);
                                    string xmlPath = targetNode.AllParentName.Substring(i);
                                    i = xmlPath.LastIndexOf(dropNode.Text);
                                    xmlPath = xmlPath.Substring(0, i - 1);
                                    xmlPath = xmlPath.Replace(",属性", "");
                                    string[] strs = xmlPath.Split(',');
                                    StringBuilder sb = new StringBuilder();
                                    foreach (var item in strs)
                                    {
                                        sb.Append("/" + item);
                                    }
                                    //目标节点路由
                                    string res2 = sb.ToString();
                                    if (!string.IsNullOrEmpty(res2))
                                    {
                                        objxml1 = doc1.SelectSingleNode(res2);
                                        if (objxml1 != null)
                                        {
                                            foreach (string item in sb1.Remove(sb1.Length - 1, 1).ToString().Split(','))
                                            {

                                                ((XmlElement)objxml1).SetAttribute(item, "");
                                            }
                                            //XmlElement objxml001 = (XmlElement)objxml1;
                                            //objxml001.SetAttribute(sourceNode.CC_Name, "");
                                        }

                                    }
                                }
                                //判断有没有属性节点
                                //获取属性节点
                                string objProperty = casecausebLL.IsHaveProperty(dropNode.Parent.Tag.ToString());
                                //如果没有属性
                                if (string.IsNullOrEmpty(objProperty))
                                {
                                    dragNode.Parent.Nodes.Remove(dragNode);
                                    casecausebLL.UpdateItemSort(sourceNode, targetNode, ms.moveNodeState);
                                    dropNode.Parent.Nodes.Insert(0, dragNode);
                                    casecausebLL.CaseCauseUpdateAllPid(dragNode.Tag.ToString());
                                    c = true;
                                    //if (dragNode.Nodes.Count > 0)
                                    //{
                                    //    TreeNodeCollection treeNodes = dragNode.Nodes;
                                    //    foreach (TreeNode item in treeNodes)
                                    //    {
                                    //        // dropNode.Parent.FirstNode.Nodes.Add(item);
                                    //        if (objxml1 != null)
                                    //        {
                                    //            XmlElement objxml001 = (XmlElement)objxml1;
                                    //            objxml001.SetAttribute(item.Text, "");
                                    //        }
                                    //    }
                                    //    casecausebLL.CaseCauseUpdateAllPid(objProperty);
                                    //}

                                }
                                else//如果存在属性
                                {
                                    if (dragNode.Nodes.Count > 0)
                                    {
                                        TreeNode attbuteNode = null;
                                        TreeNodeCollection treeNodes = dragNode.Nodes;
                                        foreach (TreeNode r in dropNode.Parent.Nodes)
                                        {
                                            if (r.Text == "属性")
                                            {
                                                attbuteNode = r;
                                                break;
                                            }
                                        }
                                        SYS_CaseCause nowNode = casecausebLL.GetCaseCauseByCCID(attbuteNode.Tag.ToString());
                                        dragNode.Parent.Nodes.Remove(dragNode);
                                        foreach (TreeNode item in treeNodes)
                                        // for(int i=0;i<treeNodes.Count;i++)
                                        {

                                            //dragNode.Nodes.Remove(treeNodes[i]);
                                            attbuteNode.Nodes.Add(item);
                                            //dropNode.Parent.FirstNode.Nodes.Add(item);

                                            if (objxml1 != null)
                                            {
                                                XmlElement objxml001 = (XmlElement)objxml1;
                                                objxml001.SetAttribute(item.Text, "");
                                            }
                                            SYS_CaseCause model = casecausebLL.GetCaseCauseByCCID(item.Tag.ToString());

                                            //赋值来源节点的内容                     
                                            model.CC_ParentID = attbuteNode.Tag.ToString();
                                            model.AllParentId = nowNode.AllParentId + "," + model.CC_ID;
                                            model.AllParentName = nowNode.AllParentName + "," + model.CC_Name;
                                            model.CC_SerialNumb = casecausebLL.GetNodeChildSerialNumber(attbuteNode.Tag.ToString());
                                            model.HW_level = model.AllParentName.Split(',').Length;

                                            //if (model.CC_NodeType == 12 || model.CC_NodeType == 11)
                                            //{
                                            if (!string.IsNullOrEmpty(caseTargetCausexml.ElementXML))
                                            {
                                                //if (model.CC_Name == "属性")
                                                //{
                                                int i;
                                                if (model.AllParentName.Contains("案由要素"))
                                                {
                                                    i = model.AllParentName.IndexOf("案由要素");
                                                }
                                                else
                                                {
                                                    i = model.AllParentName.IndexOf(caseCausexml.CC_Name);
                                                }
                                                //int i = model.AllParentName.ToString().IndexOf(caseCausexml.CC_Name);
                                                string str5 = string.Empty;
                                                if (model.CC_Name == "属性")
                                                {
                                                    str5 = model.AllParentName.ToString().Substring(i - 1).Replace(',', '/').Replace("/属性", "");
                                                }
                                                else
                                                {
                                                    str5 = model.AllParentName.ToString().Substring(i - 1).Replace(',', '/').Replace("/属性/", "/@");
                                                }
                                                model.XmlPath = str5;
                                                //}
                                            }
                                            //   }

                                            casecausebLL.UpdateSYS_CaseCause(model, Gvar.uo.m_displayName);
                                        }
                                        attbuteNode.Expand();
                                        casecausebLL.DeleteSYS_CaseCause(dragNode.Tag.ToString(), dragNode.Text.ToString(), Gvar.uo.m_displayName);

                                    }
                                }

                                if (b)
                                {
                                    if (!string.IsNullOrEmpty(doc1.InnerXml.ToString()))
                                    {
                                        string res3 = FormatXML(doc1.InnerXml.ToString());
                                        bool res = casecausebLL.UpdateElementXML(caseCausexml.CC_ID, res3);
                                    }
                                }
                                else
                                {
                                    if (!string.IsNullOrEmpty(doc.InnerXml.ToString()))
                                    {
                                        string res3 = FormatXML(doc.InnerXml.ToString());
                                        bool res = casecausebLL.UpdateElementXML(caseCausexml.CC_ID, res3);
                                    }

                                    if (!string.IsNullOrEmpty(doc1.InnerXml.ToString()))
                                    {
                                        string res3 = FormatXML(doc1.InnerXml.ToString());
                                        bool res = casecausebLL.UpdateElementXML(caseTargetCausexml.CC_ID, res3);
                                    }
                                }

                                #endregion
                            }
                        }
                        else if (ms.moveNodeState == "下级")
                        {
                            //如果来源节点是属性并且目标节点不等于属性时
                            if (sourceNode.CC_NodeType == 12 && sourceNode.CC_Name != "属性")
                            {
                                SYS_CaseCause nowNode = null;
                                //目标节点父节点xml
                                SYS_CaseCause caseNode = casecausebLL.GetCaseCauseByCCID(dragNode.Tag.ToString());
                                SYS_CaseCause caseTargetNode = casecausebLL.GetCaseCauseByCCID(dropNode.Tag.ToString());
                                var model = new SYS_CaseCause();
                                //判断有没有属性节点
                                //获取属性节点
                                if (dropNode.Text != "属性")
                                {
                                    string objProperty = casecausebLL.IsHaveProperty(dropNode.Tag.ToString());
                                    if (string.IsNullOrEmpty(objProperty))
                                    {

                                        //创建属性节点
                                        model.CC_ID = newid.JudgeDoc_CreateID("SYS_CaseCause");
                                        model.CC_Name = "属性";
                                        model.CC_ParentID = dropNode.Tag.ToString();
                                        model.CC_NodeType = 12;
                                        model.AllParentId = caseTargetNode.AllParentId + "," + model.CC_ID;
                                        model.AllParentName = caseTargetNode.AllParentName + "," + model.CC_Name;
                                        model.HW_level = model.AllParentName.Split(',').Length;
                                        model.CC_SerialNumb = 1;
                                        casecausebLL.AddPropertyUpdateSerialNum(model.CC_ParentID);

                                        //if (model.CC_NodeType == 12 || model.CC_NodeType == 11)
                                        //{
                                        if (!string.IsNullOrEmpty(caseTargetCausexml.ElementXML))
                                        {
                                            //if (model.CC_Name == "属性")
                                            //{
                                            int i;
                                            if (model.AllParentName.Contains("案由要素"))
                                            {
                                                i = model.AllParentName.IndexOf("案由要素");
                                            }
                                            else
                                            {
                                                i = model.AllParentName.IndexOf(caseCausexml.CC_Name);
                                            }
                                            //int i = model.AllParentName.ToString().IndexOf(caseCausexml.CC_Name);
                                            string str5 = string.Empty;
                                            if (model.CC_Name == "属性")
                                            {
                                                str5 = model.AllParentName.ToString().Substring(i - 1).Replace(',', '/').Replace("/属性", "");
                                            }
                                            else
                                            {
                                                str5 = model.AllParentName.ToString().Substring(i - 1).Replace(',', '/').Replace("/属性/", "/@");
                                            }
                                            model.XmlPath = str5;
                                            //}
                                        }
                                        // }

                                        if (casecausebLL.AddSYS_CaseCause(model, Gvar.uo.m_displayName))
                                        {
                                            //添加成功属性节点
                                            casecausebLL.CaseCauseUpdateAllPid(model.CC_ID);
                                            var addnode = new TreeNode();
                                            addnode.Tag = model.CC_ID;
                                            addnode.Text = model.CC_Name;
                                            addnode.Name = model.CC_NodeType.ToString();
                                            dropNode.Nodes.Insert(0, addnode);
                                            dropNode.Expand();
                                            // editnode = clicknode = addnode; 
                                            nowNode = casecausebLL.GetCaseCauseByCCID(model.CC_ID.ToString());
                                            model = new SYS_CaseCause();

                                        }
                                    }
                                    else
                                    {
                                        nowNode = casecausebLL.GetCaseCauseByCCID(objProperty);
                                    }
                                }
                                else
                                {
                                    nowNode = casecausebLL.GetCaseCauseByCCID(dropNode.Tag.ToString());
                                }
                                model = caseNode;
                                //赋值来源节点的内容                     
                                model.CC_ParentID = nowNode.CC_ID.ToString();
                                model.AllParentId = nowNode.AllParentId + "," + caseNode.CC_ID;
                                model.AllParentName = nowNode.AllParentName + "," + caseNode.CC_Name;
                                model.HW_level = model.AllParentName.Split(',').Length;
                                model.CC_SerialNumb = casecausebLL.GetNodeChildSerialNumber(nowNode.CC_ID.ToString());

                                //if (model.CC_NodeType == 12 || model.CC_NodeType == 11)
                                //{
                                if (!string.IsNullOrEmpty(caseTargetCausexml.ElementXML))
                                {
                                    //if (model.CC_Name == "属性")
                                    //{
                                    int i;
                                    if (model.AllParentName.Contains("案由要素"))
                                    {
                                        i = model.AllParentName.IndexOf("案由要素");
                                    }
                                    else
                                    {
                                        i = model.AllParentName.IndexOf(caseCausexml.CC_Name);
                                    }

                                    string str5 = string.Empty;
                                    if (model.CC_Name == "属性")
                                    {
                                        str5 = model.AllParentName.ToString().Substring(i - 1).Replace(',', '/').Replace("/属性", "");
                                    }
                                    else
                                    {
                                        str5 = model.AllParentName.ToString().Substring(i - 1).Replace(',', '/').Replace("/属性/", "/@");
                                    }
                                    model.XmlPath = str5;
                                    //}
                                }
                                else
                                {
                                    model.XmlPath = "";
                                }
                                //  }

                                TreeNode attbuteNode = null;
                                if (casecausebLL.UpdateSYS_CaseCause(model, Gvar.uo.m_displayName))
                                {
                                    // casecausebLL.CaseCauseUpdateAllPid(model.CC_ID);
                                    //   editnode.Expand();
                                    var addnode = new TreeNode();
                                    addnode.Tag = model.CC_ID;
                                    addnode.Text = model.CC_Name;
                                    addnode.Name = model.CC_NodeType.ToString();
                                    if (dropNode.Text != "属性")
                                    {
                                        foreach (TreeNode r in dropNode.Nodes)
                                        {
                                            if (r.Text == "属性")
                                            {
                                                attbuteNode = r;
                                                break;
                                            }
                                        }
                                    }
                                    else if (dropNode.Text == "属性")
                                    {
                                        attbuteNode = dropNode;
                                    }
                                    attbuteNode.Nodes.Add(addnode);
                                    attbuteNode.Expand();
                                    if (dragNode.Parent.Text == "属性" && dragNode.Parent.Nodes.Count == 1)
                                    {
                                        //删除属性节点
                                        if (casecausebLL.DeleteCaseCauseByCCId(dragNode.Parent.Tag.ToString()))
                                        {
                                            dragNode.Parent.Parent.Nodes.Remove(dragNode.Parent);
                                        }
                                    }
                                    else
                                    {
                                        dragNode.Parent.Nodes.Remove(dragNode);
                                    }
                                    //dragNode.Parent.Nodes.Remove(dragNode);
                                    //dropNode.FirstNode.Nodes.Insert(0, addnode);
                                    //dropNode.FirstNode.Expand();
                                    //tVCaseCause.SelectedNode = addnode;

                                }

                                #region 修改xml结构
                                if (!string.IsNullOrEmpty(caseCausexml.ElementXML))
                                {
                                    string xml = caseCausexml.ElementXML.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @"");
                                    doc.LoadXml(xml);

                                    int res01 = sourceNode.AllParentName.LastIndexOf(",属性");
                                    string res2 = sourceNode.AllParentName.Substring(0, res01);
                                    int i = 0;
                                    string ayysId = casecausebLL.GetAyysIDByName(caseCausexml.CC_ID);
                                    if (!string.IsNullOrEmpty(ayysId) && res2.Contains("案由要素"))
                                    {
                                        i = res2.LastIndexOf("案由要素");
                                    }
                                    else
                                    {
                                        i = res2.LastIndexOf(caseCausexml.CC_Name);
                                    }
                                    // int i = res2.LastIndexOf(caseCausexml.CC_Name);
                                    string xmlPath = res2.Substring(i);
                                    string[] strs = xmlPath.Split(',');
                                    StringBuilder sb = new StringBuilder();
                                    foreach (var item in strs)
                                    {
                                        sb.Append("/" + item);
                                    }
                                    //原节点路由
                                    string res1 = sb.ToString();
                                    if (!string.IsNullOrEmpty(res1))
                                    {
                                        objxml = doc.SelectSingleNode(res1);
                                        if (objxml != null)
                                        {
                                            XmlElement objxml001 = (XmlElement)objxml;
                                            objxml001.RemoveAttribute(sourceNode.CC_Name);
                                        }
                                    }
                                }
                                bool b = false;
                                if (!string.IsNullOrEmpty(caseTargetCausexml.ElementXML))
                                {
                                    if (caseCausexml.CC_ID == caseTargetCausexml.CC_ID)
                                    {
                                        doc1 = doc;
                                        b = true;
                                    }
                                    else
                                    {
                                        string xml = caseTargetCausexml.ElementXML.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @"");
                                        doc1.LoadXml(xml);
                                    }
                                    //int i = targetNode.AllParentName.LastIndexOf(caseTargetCausexml.CC_Name);
                                    //string xmlPath = targetNode.AllParentName.Substring(i);
                                    ////i = xmlPath.LastIndexOf(dropNode.Text);
                                    ////xmlPath = xmlPath.Substring(0, i - 1);
                                    //xmlPath = xmlPath.Replace(",属性", "");
                                    //string[] strs = xmlPath.Split(',');
                                    //StringBuilder sb = new StringBuilder();
                                    //foreach (var item in strs)
                                    //{
                                    //    sb.Append("/" + item);
                                    //}
                                    //目标节点路由
                                    string res2 = targetNode.XmlPath;
                                    if (!string.IsNullOrEmpty(res2))
                                    {
                                        objxml1 = doc1.SelectSingleNode(res2);
                                        if (objxml1 != null)
                                        {
                                            XmlElement objxml001 = (XmlElement)objxml1;
                                            objxml001.SetAttribute(sourceNode.CC_Name, "");
                                        }

                                    }
                                }
                                if (b)
                                {
                                    if (!string.IsNullOrEmpty(doc1.InnerXml.ToString()))
                                    {
                                        string res3 = FormatXML(doc1.InnerXml.ToString());
                                        bool res = casecausebLL.UpdateElementXML(caseCausexml.CC_ID, res3);
                                    }
                                }
                                else
                                {
                                    if (!string.IsNullOrEmpty(doc.InnerXml.ToString()))
                                    {
                                        string res3 = FormatXML(doc.InnerXml.ToString());
                                        bool res = casecausebLL.UpdateElementXML(caseCausexml.CC_ID, res3);
                                    }

                                    if (!string.IsNullOrEmpty(doc1.InnerXml.ToString()))
                                    {
                                        string res3 = FormatXML(doc1.InnerXml.ToString());
                                        bool res = casecausebLL.UpdateElementXML(caseTargetCausexml.CC_ID, res3);
                                    }
                                }
                                #endregion
                            }
                            else if (sourceNode.CC_NodeType == 12 && sourceNode.CC_Name == "属性")
                            {
                                if (!string.IsNullOrEmpty(caseCausexml.ElementXML))
                                {
                                    string xml = caseCausexml.ElementXML.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @"");
                                    doc.LoadXml(xml);

                                    //int res01 = sourceNode.AllParentName.LastIndexOf(",属性");
                                    //string res2 = sourceNode.AllParentName.Substring(0, res01);
                                    //int i = res2.LastIndexOf(caseCausexml.CC_Name);
                                    //string xmlPath = res2.Substring(i);
                                    //string[] strs = xmlPath.Split(',');
                                    //StringBuilder sb = new StringBuilder();
                                    //foreach (var item in strs)
                                    //{
                                    //    sb.Append("/" + item);
                                    //}
                                    //原节点路由
                                    string res1 = sourceNode.XmlPath;
                                    if (!string.IsNullOrEmpty(res1))
                                    {
                                        objxml = doc.SelectSingleNode(res1);
                                        if (objxml != null)
                                        {

                                            XmlAttributeCollection xac = objxml.Attributes;
                                            if (xac.Count > 0)
                                            {
                                                sb1.Clear();
                                                foreach (XmlAttribute xa in xac)
                                                {
                                                    sb1.Append(xa.Name + ",");
                                                }
                                            }
                                            XmlElement objxml001 = (XmlElement)objxml;
                                            objxml001.RemoveAllAttributes();
                                            objParentXml = objxml.ParentNode;
                                        }
                                    }
                                }
                                bool b = false;

                                if (!string.IsNullOrEmpty(caseTargetCausexml.ElementXML))
                                {
                                    if (caseCausexml.CC_ID == caseTargetCausexml.CC_ID)
                                    {
                                        doc1 = doc;
                                        b = true;
                                    }
                                    else
                                    {
                                        string xml = caseTargetCausexml.ElementXML.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @"");
                                        doc1.LoadXml(xml);
                                    }
                                    //int i = targetNode.AllParentName.LastIndexOf(caseTargetCausexml.CC_Name);
                                    //string xmlPath = targetNode.AllParentName.Substring(i);
                                    ////i = xmlPath.LastIndexOf(dropNode.Text);
                                    ////xmlPath = xmlPath.Substring(0, i - 1);
                                    ////xmlPath = xmlPath.Replace(",属性", "");
                                    //string[] strs = xmlPath.Split(',');
                                    //StringBuilder sb = new StringBuilder();
                                    //foreach (var item in strs)
                                    //{
                                    //    sb.Append("/" + item);
                                    //}
                                    //目标节点路由
                                    string res2 = targetNode.XmlPath;
                                    if (!string.IsNullOrEmpty(res2))
                                    {
                                        objxml1 = doc1.SelectSingleNode(res2);
                                        if (objxml1 != null)
                                        {
                                            if (!string.IsNullOrEmpty(sb1.ToString()))
                                            {
                                                foreach (string item in sb1.Remove(sb1.Length - 1, 1).ToString().Split(','))
                                                {

                                                    ((XmlElement)objxml1).SetAttribute(item, "");
                                                }

                                            }
                                            objParentXml1 = objxml1.ParentNode;

                                            //XmlElement objxml001 = (XmlElement)objxml1;
                                            //objxml001.SetAttribute(sourceNode.CC_Name, "");
                                        }

                                    }
                                    //if (objParentXml != null)
                                    //{
                                    //    objParentXml.RemoveChild(objxml);
                                    //}
                                    //if (objParentXml1 != null && objxml != null && objxml1 != null)
                                    //{
                                    //    objxml1.AppendChild(objxml);
                                    //}
                                    //判断有没有属性节点
                                    //获取属性节点
                                    string objProperty = casecausebLL.IsHaveProperty(dropNode.Tag.ToString());
                                    //如果没有属性
                                    if (string.IsNullOrEmpty(objProperty))
                                    {
                                        casecausebLL.UpdateItemSort(sourceNode, targetNode, ms.moveNodeState);
                                        dragNode.Parent.Nodes.Remove(dragNode);
                                        dropNode.Nodes.Insert(0, dragNode);
                                    }
                                    else//如果存在属性
                                    {
                                        if (dragNode.Nodes.Count > 0)
                                        {
                                            TreeNode attbuteNode = null;
                                            TreeNodeCollection treeNodes = dragNode.Nodes;
                                            foreach (TreeNode r in dropNode.Nodes)
                                            {
                                                if (r.Text == "属性")
                                                {
                                                    attbuteNode = r;
                                                    break;
                                                }
                                            }
                                            SYS_CaseCause nowNode = casecausebLL.GetCaseCauseByCCID(attbuteNode.Tag.ToString());
                                            dragNode.Parent.Nodes.Remove(dragNode);
                                            foreach (TreeNode item in treeNodes)
                                            {

                                                //dragNode.Nodes.Remove(item);
                                                attbuteNode.Nodes.Add(item);
                                                //dropNode.Parent.FirstNode.Nodes.Add(item);

                                                if (objxml1 != null)
                                                {
                                                    XmlElement objxml001 = (XmlElement)objxml1;
                                                    objxml001.SetAttribute(item.Text, "");
                                                }
                                                SYS_CaseCause model = casecausebLL.GetCaseCauseByCCID(item.Tag.ToString());

                                                //赋值来源节点的内容                     
                                                model.CC_ParentID = attbuteNode.Tag.ToString();
                                                model.AllParentId = nowNode.AllParentId + "," + model.CC_ID;
                                                model.AllParentName = nowNode.AllParentName + "," + model.CC_Name;
                                                model.HW_level = model.AllParentName.Split(',').Length;
                                                model.CC_SerialNumb = casecausebLL.GetNodeChildSerialNumber(attbuteNode.Tag.ToString());


                                                //if (model.CC_NodeType == 12 || model.CC_NodeType == 11)
                                                //{
                                                if (!string.IsNullOrEmpty(caseTargetCausexml.ElementXML))
                                                {
                                                    //if (model.CC_Name == "属性")
                                                    //{
                                                    int i = 0;
                                                    if (model.AllParentName.Contains("案由要素"))
                                                    {
                                                        i = model.AllParentName.IndexOf("案由要素");
                                                    }
                                                    else
                                                    {
                                                        i = model.AllParentName.IndexOf(caseCausexml.CC_Name);
                                                    }

                                                    string str5 = string.Empty;
                                                    if (model.CC_Name == "属性")
                                                    {
                                                        str5 = model.AllParentName.ToString().Substring(i - 1).Replace(',', '/').Replace("/属性", "");
                                                    }
                                                    else
                                                    {
                                                        str5 = model.AllParentName.ToString().Substring(i - 1).Replace(',', '/').Replace("/属性/", "/@");
                                                    }
                                                    model.XmlPath = str5;
                                                    //}
                                                }
                                                // }

                                                casecausebLL.UpdateSYS_CaseCause(model, Gvar.uo.m_displayName);
                                            }
                                            attbuteNode.Expand();
                                            casecausebLL.DeleteSYS_CaseCause(dragNode.Tag.ToString(), dragNode.Text.ToString(), Gvar.uo.m_displayName);
                                        }
                                        else
                                        {
                                            dragNode.Parent.Nodes.Remove(dragNode);
                                        }
                                    }
                                }

                                if (b)
                                {
                                    if (!string.IsNullOrEmpty(doc1.InnerXml.ToString()))
                                    {
                                        string res3 = FormatXML(doc1.InnerXml.ToString());
                                        bool res = casecausebLL.UpdateElementXML(caseCausexml.CC_ID, res3);
                                    }
                                }
                                else
                                {
                                    if (!string.IsNullOrEmpty(doc.InnerXml.ToString()))
                                    {
                                        string res3 = FormatXML(doc.InnerXml.ToString());
                                        bool res = casecausebLL.UpdateElementXML(caseCausexml.CC_ID, res3);
                                    }

                                    if (!string.IsNullOrEmpty(doc1.InnerXml.ToString()))
                                    {
                                        string res3 = FormatXML(doc1.InnerXml.ToString());
                                        bool res = casecausebLL.UpdateElementXML(caseTargetCausexml.CC_ID, res3);
                                    }
                                }
                            }


                        }
                    }
                    else
                    {
                        if (casecausebLL.UpdateItemSort(sourceNode, targetNode, ms.moveNodeState))
                        {
                            double sourceSort = sourceNode.CC_SerialNumb;
                            double targetSort = targetNode.CC_SerialNumb;
                            switch (ms.moveNodeState)
                            {
                                case "上方":
                                    dragNode.Parent.Nodes.Remove(dragNode);
                                    //if (sourceSort < targetSort)
                                    //{
                                    dropNode.Parent.Nodes.Insert(dropNode.Index, dragNode);
                                    //}else
                                    //{
                                    //    dropNode.Parent.Nodes.Insert(dropNode.Index)
                                    //}
                                    break;
                                case "下方":
                                    dragNode.Parent.Nodes.Remove(dragNode);
                                    dropNode.Parent.Nodes.Insert(dropNode.Index + 1, dragNode);
                                    break;
                                case "下级":
                                    dragNode.Parent.Nodes.Remove(dragNode);
                                    dropNode.Nodes.Add(dragNode);
                                    break;
                            }
                        }
                    }


                    //修改节点的案由下面的xmlPath
                    casecausebLL.UpdateXmlPath((casecausebLL.IsParentRealation1(dropNode.Tag.ToString())).CC_ID);
                }

                //SYS_CaseCause dragItem = GetCauseItem(m_dragNode.Tag.ToString());
                //SYS_CaseCause dropItem = GetCauseItem(dropNode.Tag.ToString());
                //int dropIndex = dropNode.Index;
                ////如果是冲下往上移
                //if (SYSCaseCauseBLL.UpdateItemSort(dragItem, dropItem))
                //{
                //    dropNode.Parent.Nodes.Remove(m_dragNode);
                //    dropNode.Parent.Nodes.Insert(dropNode.Index, m_dragNode);
                //}
                ////如果是冲上往下移
                //else
                //{
                //    dropNode.Parent.Nodes.Remove(m_dragNode);
                //    dropNode.Parent.Nodes.Insert(dropNode.Index + 1, m_dragNode);
                //}
            }
            //设置选中节点
            tVCaseCause.SelectedNode = dragNode;
            clicknode = dragNode;
            this.m_timer.Enabled = false;
            dropNode.ForeColor = dropNodeColor;
            dragNode.ForeColor = dragNodeColor;
            //移动完成更新缓存，使缓存和数据库保持一致
            // GetCause(m_dragNode.Name, true);


        }
        #endregion

        #region 将字符串转换为XML格式字符串
        /// <summary>
        /// 将字符串转换为XML格式字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public string FormatXML(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(str);
                StringBuilder strbu = new StringBuilder();
                System.IO.StringWriter stringWriter = new System.IO.StringWriter(strbu);
                System.Xml.XmlTextWriter xmlWriter = new System.Xml.XmlTextWriter(stringWriter);
                xmlWriter.Formatting = System.Xml.Formatting.Indented;
                doc.WriteTo(xmlWriter);
                return strbu.ToString();
            }
            else
            {
                return str;
            }
        }
        #endregion

        #region 类别选项改变项事件
        /// <summary>
        /// 类别选项改变项事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NodeTypeList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if ((NodeTypeList.Text == "XML节点" || NodeTypeList.Text == "XML属性") && Childname.Text != "属性")
            {
                DataTable caseCauseTable = casecausebLL.GetCaseCauseTypeByNodeType();
                if (caseCauseTable != null && caseCauseTable.Rows.Count > 0)
                {
                    label39.Visible = true;
                    NodeSubTypeList.Visible = true;
                    NodeSubTypeList.DataSource = caseCauseTable;
                    NodeSubTypeList.DisplayMember = "CC_NodeTypeName";
                    NodeSubTypeList.ValueMember = "CC_NodeType";
                    //  cbNodeType2.SelectedValue = -1;
                    cmbName.Visible = false;
                    Childname.Visible = true;
                    panelBase.Visible = false;
                    panelType.Location = new System.Drawing.Point(0, 187);
                    //判断父节点是否是相应要素则默认改变
                    if (clicknode.FullPath != null && clicknode.FullPath.Contains("诉请要素"))
                    {
                        NodeSubTypeList.Text = "诉请要素";
                    }
                    else if (clicknode.FullPath != null && clicknode.FullPath.Contains("事实要素"))
                    {
                        NodeSubTypeList.Text = "事实要素";
                    }
                    else if (clicknode.FullPath != null && clicknode.FullPath.Contains("基本要素"))
                    {
                        NodeSubTypeList.Text = "基本要素";
                    }
                    else if (clicknode.FullPath != null && clicknode.FullPath.Contains("结果要素"))
                    {
                        NodeSubTypeList.Text = "结果要素";
                    }
                }

            }
            else if (NodeTypeList.Text == "裁判理由")
            {
                if (table1.Count > 0)
                {
                    label39.Visible = true;
                    NodeSubTypeList.Visible = true;
                    NodeSubTypeList.DataSource = table1;
                    cmbName.Visible = true;
                    Childname.Visible = false;
                    NodeSubTypeList.SelectedIndex = 0;
                    if (dic.ContainsKey(NodeSubTypeList.Text))
                    {
                        cmbName.DataSource = dic[NodeSubTypeList.Text];
                    }
                    panelBase.Visible = false;
                    panelType.Location = new System.Drawing.Point(0, 187);
                }
            }
            else if (NodeTypeList.Text == "裁判结果")
            {
                if (dic1.Count > 0)
                {
                    label39.Visible = false;
                    NodeSubTypeList.Visible = false;
                    //label39.Visible = true;
                    //NodeSubTypeList.Visible = true;
                    //NodeSubTypeList.DataSource = dic1["裁判结果"];
                    cmbName.Visible = true;
                    Childname.Visible = false;
                    if (dic1.ContainsKey("裁判结果"))
                    {
                        cmbName.DataSource = dic1["裁判结果"];
                    }
                    cmbName.SelectedIndex = 0;
                    panelBase.Visible = false;
                    panelType.Location = new System.Drawing.Point(0, 187);
                }
            }
            else
            {
                label39.Visible = false;
                NodeSubTypeList.Visible = false;
                //NodeSubTypeList.SelectedValue = 0;
                cmbName.Visible = false;
                Childname.Visible = true;
                panelBase.Visible = false;
                panelType.Location = new System.Drawing.Point(0, 187);
            }
        }
        #endregion

        #region 名称文本框改变事件
        //名称文本框改变事件
        private void Childname_TextChanged(object sender, EventArgs e)
        {
            if (clicknode.Parent != null)
            {
                if (clicknode.Parent.Text != "属性")
                {
                    if (clicknode.Text != "属性")
                    {
                        if (Childname.Text == "属性")
                        {
                            NodeTypeList.SelectedValue = "12";
                            NodeTypeList.Enabled = false;
                            label39.Visible = false;
                            NodeSubTypeList.Visible = false;
                            NodeSubTypeList.SelectedValue = 0;
                        }
                        else
                        {

                            NodeTypeList.Enabled = true;
                            if (NodeTypeList.SelectedValue != null)
                            {
                                if (NodeTypeList.SelectedValue.ToString() == "12")
                                {
                                    DataTable caseCauseTable = casecausebLL.GetCaseCauseTypeByNodeType();
                                    if (caseCauseTable != null && caseCauseTable.Rows.Count > 0)
                                    {
                                        label39.Visible = true;
                                        NodeSubTypeList.Visible = true;
                                        NodeSubTypeList.DataSource = caseCauseTable;
                                        NodeSubTypeList.DisplayMember = "CC_NodeTypeName";
                                        NodeSubTypeList.ValueMember = "CC_NodeType";
                                        //  cbNodeType2.SelectedValue = -1;

                                    }
                                }
                            }
                        }
                    }
                }
            }

        }
        #endregion

        #region 跳转输入框只能输入数字
        /// <summary>
        /// 跳转输入框只能输入数字
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SkipNumber_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                e.Handled = true;
            }
        }
        #endregion

        #region 保存非同步节点
        /// <summary>
        /// 保存非同步节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveNodes_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtXML.Text.Trim() != "")
                {
                    SYS_CaseCause sourceNode = casecausebLL.GetCaseCauseByCCID(clicknode.Tag.ToString());

                    //  clicknode.Nodes.Clear();
                    this.Cursor = Cursors.WaitCursor;
                    string XMLText = txtXML.Text.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @"");
                    XmlDocument document = new XmlDocument();
                    document.LoadXml(XMLText);
                    bool res = false, res1 = false;
                    if (document.DocumentElement.Name == clicknode.Text)
                    {
                        XmlNodeList list = document.GetElementsByTagName(clicknode.Text);
                        if (list.Count > 0)
                        {
                            DataTable dt = trbll.NodeTree_Tree(clicknode.Tag.ToString());
                            if (dt != null && dt.Rows.Count > 0)
                            {
                                foreach (DataRow dr in dt.Rows)
                                {
                                    if (dr["name"].ToString() == "争议焦点要素")
                                    {
                                        res = true;
                                        continue;
                                    }
                                    //else
                                    //{
                                    //    XmlNodeList xnl = document.GetElementsByTagName("争议焦点要素");
                                    //    analysisXML.AnalyAddXMLNode(xnl, clicknode.Tag.ToString(), clicknode.Text, Gvar.uo.m_displayName);
                                    //}
                                    if (dr["name"].ToString() == "基本要素")
                                    {
                                        res1 = true;
                                        continue;
                                    }
                                    //else
                                    //{
                                    //    XmlNodeList xnl = document.GetElementsByTagName("基本要素");
                                    //    analysisXML.AnalyAddXMLNode(xnl, clicknode.Tag.ToString(), clicknode.Text, Gvar.uo.m_displayName);
                                    //}
                                }

                            }
                            XmlNodeList xnl = document.GetElementsByTagName("争议焦点要素");
                            if (!res)
                            {
                                if (xnl.Count > 0)
                                {
                                    //不存在，先新增争议焦点要素
                                    SYS_CaseCause NewModel = new SYS_CaseCause();
                                    NewModel.CC_ID = newid.JudgeDoc_CreateID("SYS_CaseCause");
                                    NewModel.CC_Name = "争议焦点要素";
                                    NewModel.CC_ParentID = clicknode.Tag.ToString();
                                    NewModel.isLeafNode = 0;
                                    NewModel.CC_NodeType = 11;
                                    NewModel.XmlPath = clicknode.Text + @"/" + "争议焦点要素";
                                    NewModel.CC_SerialNumb = casecausebLL.ComputeSerialNumb(NewModel.CC_ParentID, "");
                                    casecausebLL.AddSYS_CaseCause(NewModel, Gvar.uo.m_displayName);
                                    analysisXML.AnalyAddXMLNode(xnl, NewModel.CC_ID, NewModel.CC_Name, Gvar.uo.m_displayName);
                                }
                            }
                            XmlNodeList xnl1 = document.GetElementsByTagName("基本要素");
                            if (!res1)
                            {
                                if (xnl1.Count > 0)
                                {
                                    SYS_CaseCause NewModel = new SYS_CaseCause();
                                    NewModel.CC_ID = newid.JudgeDoc_CreateID("SYS_CaseCause");
                                    NewModel.CC_Name = "基本要素";
                                    NewModel.CC_ParentID = clicknode.Tag.ToString();
                                    NewModel.isLeafNode = 0;
                                    NewModel.CC_NodeType = 11;
                                    NewModel.XmlPath = clicknode.Text + @"/" + "基本要素";
                                    NewModel.CC_SerialNumb = casecausebLL.ComputeSerialNumb(NewModel.CC_ParentID, "");
                                    casecausebLL.AddSYS_CaseCause(NewModel, Gvar.uo.m_displayName);
                                    analysisXML.AnalyAddXMLNode(xnl1, NewModel.CC_ID, NewModel.CC_Name, Gvar.uo.m_displayName);
                                }
                            }
                            //操作数据库进行更新xml文档
                            //bool res = casecausebLL.UpdateElementXML(clicknode.Tag.ToString(), txtXML.Text);
                            //if (res)
                            //{
                            this.Cursor = Cursors.Default;
                            if (res && res1)
                            {
                                MessageBox.Show("该节点下已存在争议焦点要素与基本要素！");
                                return;
                            }
                            if (res)
                            {
                                MessageBox.Show("该节点下已存在争议焦点要素！");
                                return;
                            }
                            if (res1)
                            {
                                MessageBox.Show("该节点下已存在基本要素！");
                                return;
                            }
                            if (xnl.Count > 0 || xnl1.Count > 0)
                            {
                                MessageBox.Show("添加成功，查看请刷新节点树!");
                                return;
                            }
                            else
                            {
                                MessageBox.Show("xml结构未包含争议焦点要素或基本要素!");
                                return;
                            }
                            // }
                        }

                    }
                    else
                    {
                        MsgBox.Err("添加失败！事实要素XML模板内容与" + clicknode.Text + "不匹配！");
                        return;
                    }
                }
                else
                {
                    MsgBox.Err("事实要素xml模版内容为空！");
                    return;
                }
            }
            catch (Exception error)
            {
                MsgBox.Err("添加失败!" + error.Message);
                return;

            }
        }
        #endregion

        #region 自动配置
        /// <summary>
        /// 自动配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConfig_Click(object sender, EventArgs e)
        {
            //如果是民事案由
            try
            {
                if (casecausebLL.IsCivilCase(clicknode.Tag.ToString()))
                {
                    var dt = casecausebLL.GetSYS_CaseCauseByCCID(clicknode.Tag.ToString());
                    string XMLText = LdFormat.ObjectToString(dt.Rows[0]["ElementXML"]);
                    if (!string.IsNullOrEmpty(XMLText))
                    {
                        hbdwKeyWord = xsdwKeyWord = string.Empty;
                        XMLText = XMLText.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @"");
                        XmlDocument document = new XmlDocument();
                        document.LoadXml(XMLText);
                        ar.Clear();

                        GetAttributes(document.DocumentElement, "/" + clicknode.Text);
                        SYS_ArgumentType Model = new SYS_ArgumentType();
                        Dictionary<string, string> dc = new Dictionary<string, string>();
                        if (ar.Count > 0)
                        {

                            if (!hasattribute)
                            {
                                MessageBox.Show("要素XML没有需要配置的字典值!");
                                return;
                            }
                            nodetree_argumenttypebll.DeleteSysArgumentType(clicknode.Tag.ToString());
                            if (hasXSDI)
                            {
                                DataTable argumenttypedt = nodetree_argumenttypebll.GetList(clicknode.Tag.ToString(), "诉讼地位");
                                if (argumenttypedt != null && argumenttypedt.Rows.Count > 0)
                                {
                                    DataRow dr = argumenttypedt.Select("AT_Name = '诉讼地位'").FirstOrDefault();
                                    xsdwKeyWord = dr["AT_MatchKeyWord"].ToString();
                                    dc.Add("诉讼地位", dr["AT_Code"].ToString());
                                }
                                if (string.IsNullOrEmpty(xsdwKeyWord))
                                {
                                    xsdwKeyWord = argumenttypexmlbll.GetSSDWKeyWord();
                                    Model.AT_ID = newidbll.JudgeDoc_CreateID("SYS_ArgumentType");
                                    Model.AT_Name = "诉讼地位";
                                    Model.AT_Code = nodetree_argumenttypebll.GetArgumentTypeNumber(clicknode.Tag.ToString(), clicknode.Text, Model.AT_Name);
                                    Model.AT_MatchKeyWord = xsdwKeyWord;
                                    Model.AT_ShowIndex = nodetree_argumenttypebll.GetAT_ShowIndex();
                                    Model.AT_CauseID = clicknode.Tag.ToString();
                                    nodetree_argumenttypebll.AddArgument(Model);
                                    dc.Add(Model.AT_Name, Model.AT_Code);
                                }

                            }
                            if (hasHBDW)
                            {
                                DataTable argumenttypedt = nodetree_argumenttypebll.GetList(clicknode.Tag.ToString(), "货币单位");
                                if (argumenttypedt != null && argumenttypedt.Rows.Count > 0)
                                {
                                    DataRow dr = argumenttypedt.Select("AT_Name = '货币单位'").FirstOrDefault();
                                    hbdwKeyWord = dr["AT_MatchKeyWord"].ToString();
                                    dc.Add("货币单位", dr["AT_Code"].ToString());
                                }
                                if (string.IsNullOrEmpty(hbdwKeyWord))
                                {
                                    hbdwKeyWord = argumenttypexmlbll.GetHBDWKeyWord();
                                    Model.AT_ID = newidbll.JudgeDoc_CreateID("SYS_ArgumentType");
                                    Model.AT_Name = "货币单位";
                                    Model.AT_Code = nodetree_argumenttypebll.GetArgumentTypeNumber(clicknode.Tag.ToString(), clicknode.Text, Model.AT_Name);
                                    Model.AT_MatchKeyWord = hbdwKeyWord;
                                    Model.AT_ShowIndex = nodetree_argumenttypebll.GetAT_ShowIndex();
                                    Model.AT_CauseID = clicknode.Tag.ToString();
                                    nodetree_argumenttypebll.AddArgument(Model);
                                    dc.Add(Model.AT_Name, Model.AT_Code);
                                }
                            }
                            StringBuilder sb = new StringBuilder();
                            for (int i = 0; i < ar.Count; i++)
                            {
                                if (((xmlNode)ar[i]).AttributeName == "诉讼请求明细序号")
                                {
                                    sb.Append(sxqqmxxh.Replace("???", ((xmlNode)ar[i]).XmlPath));
                                }
                                else if (((xmlNode)ar[i]).AttributeName.Contains("金额"))
                                {
                                    sb.Append(jerqzh.Replace("???", ((xmlNode)ar[i]).XmlPath));
                                }
                                else if (((xmlNode)ar[i]).AttributeName.Contains("时间"))
                                {
                                    sb.Append(rqgszh.Replace("???", ((xmlNode)ar[i]).XmlPath));
                                }
                                else if (((xmlNode)ar[i]).AttributeName.Contains("日期"))
                                {
                                    sb.Append(rqgszh.Replace("???", ((xmlNode)ar[i]).XmlPath));
                                }
                                else if (((xmlNode)ar[i]).AttributeName.Contains("货币单位"))
                                {
                                    sb.Append((qtzdzpz.Replace("???", ((xmlNode)ar[i]).XmlPath)).Replace("xxx", dc["货币单位"]));
                                }
                                else if (((xmlNode)ar[i]).AttributeName.Contains("诉讼地位"))
                                {
                                    DataSet ds = casecausebLL.GetXpath(((xmlNode)ar[i]).XmlPath);
                                    if (ds != null && ds.Tables.Count > 0)
                                    {
                                        //父节点XPath
                                        if (ds.Tables[0].Rows.Count > 0)
                                        {
                                            sb.Append(fryjd.Replace("???", ds.Tables[0].Rows[0][0].ToString()));
                                        }
                                        //同级节点XPath
                                        if (ds.Tables[1].Rows.Count > 0)
                                        {
                                            foreach (DataRow dr in ds.Tables[1].Rows)
                                            {
                                                sb.Append(tjryjd.Replace("???", dr[0].ToString()));
                                            }
                                        }
                                        sb.Append((ryjd.Replace("???", ((xmlNode)ar[i]).XmlPath)).Replace("xxx", dc["诉讼地位"]));
                                    }
                                }
                                else
                                {

                                    Model.AT_ID = newidbll.JudgeDoc_CreateID("SYS_ArgumentType");
                                    Model.AT_Name = ((xmlNode)ar[i]).AttributeName;
                                    Model.AT_Code = nodetree_argumenttypebll.GetArgumentTypeNumber(clicknode.Tag.ToString(), clicknode.Text, Model.AT_Name);
                                    Model.AT_MatchKeyWord = ((xmlNode)ar[i]).AttributeValue.Replace(" ", "");
                                    Model.AT_ShowIndex = nodetree_argumenttypebll.GetAT_ShowIndex();
                                    Model.AT_CauseID = clicknode.Tag.ToString();
                                    string str2 = argumenttypexmlbll.GetZiDianZhi(Model.AT_Name, Model.AT_CauseID, Model.AT_MatchKeyWord);
                                    if (!string.IsNullOrEmpty(str2))
                                    {
                                        if (!dc.ContainsKey(Model.AT_Name))
                                        {
                                            dc.Add(Model.AT_Name, str2);
                                        }
                                        sb.Append((qtzdzpz.Replace("???", ((xmlNode)ar[i]).XmlPath)).Replace("xxx", dc[Model.AT_Name]));
                                    }
                                    else
                                    {
                                        nodetree_argumenttypebll.AddArgument(Model);
                                        sb.Append((qtzdzpz.Replace("???", ((xmlNode)ar[i]).XmlPath)).Replace("xxx", Model.AT_Code));
                                    }
                                }
                                // xa.Name.Contains("诉讼地位") || xa.Name.Contains("货币单位") || xa.Name.Contains("金额") || xa.Name.Contains("时间") 
                                //|| xa.Name.Contains("日期") || xa.Name.Equals("诉讼请求明细序号"))
                            }
                            txt_ArgumentTypeXml.Text = FormatXML("<elementConfig>" + sb.ToString() + "</elementConfig>").Replace(" ", "").Replace("xmlPath", " xmlPath");
                            var Againlist = "";
                            if (txt_ArgumentTypeXml.Text.Trim() != "")
                            {
                                Againlist = analysisXML.AnalyArgumentTypeXml(txt_ArgumentTypeXml.Text);
                            }

                            if (Againlist.Contains("xmlPath"))
                            { MessageBox.Show(Againlist); }
                            else
                            {
                                casecausebLL.UpdateConfigXML(clicknode.Tag.ToString(), txt_ArgumentTypeXml.Text);
                                dataPagerMain.ChangePageNumber(1);
                            }
                            GetDoucumentText(document.DocumentElement);
                            string str = FormatXML(document.InnerXml);
                            bool res = casecausebLL.UpdateElementXML(clicknode.Tag.ToString(), str);

                            MessageBox.Show("自动配置成功!");
                            return;
                        }


                    }
                    else
                    {
                        MessageBox.Show("该案由下没有事实要素XML");
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("不是民事案由下的案由不能自动配置");
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("自动配置失败!" + ex.Message);
                return;
            }

        }
        #endregion

        #region 获取XML节点属性
        public void GetDoucumentText(XmlNode xn)
        {
            if (xn.HasChildNodes)
            {
                foreach (XmlNode xn1 in xn.ChildNodes)
                {
                    if (xn1.Attributes.Count > 0)
                    {
                        for (int i = 0; i < xn1.Attributes.Count; i++)
                        {
                            xn1.Attributes[i].Value = "";
                        }
                    }
                    if (xn1.HasChildNodes)
                    {
                        GetDoucumentText(xn1);
                    }
                }
            }
        }
        #endregion

        #region 操作xml属性相关
        public void GetAttributes(XmlNode xn, string xmlPath)
        {
            string str = xmlPath;
            if (xn.HasChildNodes)
            {
                foreach (XmlNode xn1 in xn.ChildNodes)
                {
                    //if (xn1.HasChildNodes)
                    //{
                    //    str += ("/" + xn1.Name);
                    //}
                    if (xn1.Attributes.Count > 0)
                    {
                        foreach (XmlAttribute xa in xn1.Attributes)
                        {
                            xmlNode xn2 = new xmlNode { AttributeName = xa.Name, AttributeValue = xa.Value.Trim(), XmlPath = GetNode(xn1) + "/@" + xa.Name };
                            if (xa.Name.Contains("诉讼地位"))
                            {
                                hasXSDI = true;
                            }
                            if (xa.Name.Contains("货币单位"))
                            {
                                hasHBDW = true;
                            }
                            if (xa.Name.Contains("诉讼请求明细序号"))
                            {
                                hassxmxxh = true;
                            }
                            if (!string.IsNullOrEmpty(xn2.AttributeValue) || xa.Name.Contains("诉讼地位") || xa.Name.Contains("货币单位") || xa.Name.Contains("金额") || xa.Name.Contains("时间") || xa.Name.Contains("日期") || xa.Name.Equals("诉讼请求明细序号"))
                            {
                                if (!string.IsNullOrEmpty(xn2.AttributeValue))
                                {
                                    hasattribute = true;
                                }
                                ar.Add(xn2);
                            }
                        }
                    }
                    if (xn1.HasChildNodes)
                    {
                        GetAttributes(xn1, str);
                    }
                }
            }
        }

        string str = string.Empty;
        public string GetNode(XmlNode xn1)
        {
            str = "";
            GetParentNode(xn1);
            return str + "/" + xn1.Name;
        }
        public void GetParentNode(XmlNode xn1)
        {
            if (xn1.ParentNode != null)
            {
                str = ("/" + xn1.ParentNode.Name) + str;
                if (!string.IsNullOrEmpty(xn1.ParentNode.ParentNode.Name) && xn1.ParentNode.Name != clicknode.Text)
                {
                    GetParentNode(xn1.ParentNode);
                }
            }
        }
        #endregion

        #region 添加来源单击事件
        /// <summary>
        /// 添加来源单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSource_Click_1(object sender, EventArgs e)
        {
            this.contextMenuStrip2.Show(btnSource, 0, this.btnSource.Height);
        }
        #endregion

        #region 手动添加事件
        /// <summary>
        /// 手动添加事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 手动添加ToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            btnSource_Click(sender, e);
        }
        #endregion

        #region 一键添加事件
        /// <summary>
        /// 一键添加事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 一键添加ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            try
            {
                FrmSourceDefaultSetting fs = new FrmSourceDefaultSetting(1);
                fs.ClickNode = clicknode;
                var dialogResult = fs.ShowDialog();
                ShowTab_Extract();
            }
            catch (Exception ex)
            {
                throw new Exception("添加失败：" + ex.Message);
            }


        }
        #endregion

        #region 设置进度条状态
        //private void SleetT()
        //{
        //    SetTextMessage(0);
        //}

        //private delegate void SetPos(int ipos);
        ///// <summary>
        ///// 设置进度条状态
        ///// </summary>
        ///// <param name="v1"></param>
        //private void SetTextMessage(int v1)
        //{
        //    if (this.InvokeRequired)
        //    {
        //        SetPos setpos = new SetPos(SetTextMessage);
        //        this.Invoke(setpos, new object[] { v1 });
        //    }
        //    else
        //    {
        //        this.progressBar2.Value = Convert.ToInt32(v1);
        //    }
        //}
        #endregion

        #region 导出EXCEL表格事件
        /// <summary>
        /// 导出EXCEL表格事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 导出Excel表格ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

        }
        #endregion

        #region 导出SQL文件
        /// <summary>
        /// 导出SQL文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 导出SQL文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            StringBuilder sb = new StringBuilder();
            StringBuilder sb1 = new StringBuilder();
            string caseCauseColumns = PublicMethod.GetColumnNameByTable("Ldt_JudgeDocSystem", "SYS_CaseCause");
            string sysExpressSourceColumns = PublicMethod.GetColumnNameByTable("Ldt_JudgeDocSystem", "SYS_Express_Source");
            string regInfoUnitColumns = PublicMethod.GetColumnNameByTable("LdtCommonManage", "Reg_InfoUnit");
            string regInfoRegexRelationColumns = PublicMethod.GetColumnNameByTable("LdtCommonManage", "Reg_InfoRegexRelation");
            string regRegexsColumns = PublicMethod.GetColumnNameByTable("LdtCommonManage", "Reg_Regexs");
            string excelZYName = clicknode.Tag.ToString() + "争议焦点";
            DataSet ZYDataSet = new DataSet();
            string excelZPName = clicknode.Tag.ToString() + "裁判理由";
            DataSet ZPDataSet = new DataSet();
            string excelXQName = clicknode.Tag.ToString() + "诉请要素";
            DataSet XQDataSet = new DataSet();
            string excelSSName = clicknode.Tag.ToString() + "事实要素";
            DataSet SSDataSet = new DataSet();
            string excelJBName = clicknode.Tag.ToString() + "基本要素";
            DataSet JBDataSet = new DataSet();
            DataTable dt = casecausebLL.GetDaoChuData(clicknode.Tag.ToString(), "争议焦点");

            DataTable SYS_CaseCause = dt.Clone();
            SYS_CaseCause.TableName = "SYS_CaseCause";
            ZYDataSet.Tables.Add(SYS_CaseCause);
            DataTable SYS_CaseCause1 = dt.Clone();
            SYS_CaseCause1.TableName = "SYS_CaseCause";
            ZPDataSet.Tables.Add(SYS_CaseCause1);
            DataTable SYS_CaseCause2 = dt.Clone();
            SYS_CaseCause2.TableName = "SYS_CaseCause";
            XQDataSet.Tables.Add(SYS_CaseCause2);
            DataTable SYS_CaseCause3 = dt.Clone();
            SYS_CaseCause3.TableName = "SYS_CaseCause";
            SSDataSet.Tables.Add(SYS_CaseCause3);
            DataTable SYS_CaseCause4 = dt.Clone();
            SYS_CaseCause4.TableName = "SYS_CaseCause";
            JBDataSet.Tables.Add(SYS_CaseCause4);

            //获取各个类型下的数据
            //争议焦点
            if (dt != null && dt.Rows.Count > 0)
            {
                NewMethod(sb, sb1, caseCauseColumns, sysExpressSourceColumns, regInfoUnitColumns, regInfoRegexRelationColumns, regRegexsColumns, dt, "争议焦点", ZYDataSet);
            }
            //裁判理由
            dt = casecausebLL.GetDaoChuData(clicknode.Tag.ToString(), "裁判理由");
            if (dt != null && dt.Rows.Count > 0)
            {
                NewMethod(sb, sb1, caseCauseColumns, sysExpressSourceColumns, regInfoUnitColumns, regInfoRegexRelationColumns, regRegexsColumns, dt, "裁判理由", ZPDataSet);
            }
            //诉请要素
            dt = casecausebLL.GetDaoChuSecondData(clicknode.Tag.ToString(), "诉请要素");
            if (dt != null && dt.Rows.Count > 0)
            {
                NewMethod(sb, sb1, caseCauseColumns, sysExpressSourceColumns, regInfoUnitColumns, regInfoRegexRelationColumns, regRegexsColumns, dt, "诉请要素", XQDataSet);
            }
            //事实要素
            dt = casecausebLL.GetDaoChuSecondData(clicknode.Tag.ToString(), "事实要素");
            if (dt != null && dt.Rows.Count > 0)
            {
                NewMethod(sb, sb1, caseCauseColumns, sysExpressSourceColumns, regInfoUnitColumns, regInfoRegexRelationColumns, regRegexsColumns, dt, "事实要素", SSDataSet);
            }
            //基本要素
            dt = casecausebLL.GetDaoChuSecondData(clicknode.Tag.ToString(), "基本要素");
            if (dt != null && dt.Rows.Count > 0)
            {
                NewMethod(sb, sb1, caseCauseColumns, sysExpressSourceColumns, regInfoUnitColumns, regInfoRegexRelationColumns, regRegexsColumns, dt, "基本要素", JBDataSet);
            }
            string strSql = string.Format(@"use Ldt_JudgeDocSystem
GO 
SET XACT_ABORT ON
GO  
BEGIN TRANSACTION  Rebuid_9633097;   
{0} 
IF (@@ERROR <> 0) 
GOTO ERROR_9633097 
 
COMMIT TRAN Rebuid_9633097 
GOTO OK_9633097 
 
ERROR_9633097: 
ROLLBACK TRAN Rebuid_9633097 
 
OK_9633097: 
GO 
                 ", sb.ToString());
            if (!string.IsNullOrEmpty(strSql) && ((ToolStripMenuItem)sender).Text == "导出SQL文件")
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                //打开的文件选择对话框上的标题  
                saveFileDialog.Title = "导出到";
                //设置文件类型  
                saveFileDialog.Filter = "SQLSERVER脚本文件(*.sql)|所有文件(*.*)";
                //设置默认文件类型显示顺序  
                saveFileDialog.FilterIndex = 1;
                //保存对话框是否记忆上次打开的目录  
                saveFileDialog.RestoreDirectory = true;
                //设置是否允许多选  
                //saveFileDialog.Multiselect = false;
                saveFileDialog.FileName = clicknode.Tag.ToString() + ".sql";
                //按下确定选择的按钮  
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    //获得文件路径  
                    string localFilePath = saveFileDialog.FileName.ToString();

                    if (!File.Exists(localFilePath))
                    {
                        StreamWriter sw = new StreamWriter(localFilePath, false, Encoding.Unicode);
                        sw.WriteLine(strSql);
                        sw.Close();
                        MessageBox.Show("导出表数据成功！导出路径：" + localFilePath);
                    }
                    else
                    {
                        StreamWriter sw = new StreamWriter(localFilePath, false, Encoding.Unicode);
                        sw.WriteLine(strSql);
                        sw.Close();
                        MessageBox.Show("导出表数据成功！导出路径：" + localFilePath);
                    }
                }
            }
            else if (((ToolStripMenuItem)sender).Text == "导出Excel表格")
            {
                //string str = ExcelHelper.GetSaveFilePath();

                SaveFileDialog saveFileDig = new SaveFileDialog();
                saveFileDig.Filter = "Excel Office2007及以上(*.xlsx)|*.xlsx";
                saveFileDig.FilterIndex = 1;
                saveFileDig.Title = "导出到";
                saveFileDig.OverwritePrompt = true;
                saveFileDig.FileName = clicknode.Tag.ToString() + "争议焦点" + ".xlsx";
                // saveFileDig.InitialDirectory = DesktopDirectory;
                //string filePath = null;
                if (saveFileDig.ShowDialog() == DialogResult.OK)
                {
                    string filePath = saveFileDig.FileName;
                    //争议焦点
                    ExcelHelper.ExportToExcel(ZYDataSet, filePath);
                    //裁判理由
                    ExcelHelper.ExportToExcel(ZPDataSet, filePath.Replace("争议焦点", "裁判理由"));
                    //诉请要素
                    ExcelHelper.ExportToExcel(XQDataSet, filePath.Replace("争议焦点", "诉请要素"));
                    //事实要素
                    ExcelHelper.ExportToExcel(SSDataSet, filePath.Replace("争议焦点", "事实要素"));
                    //基本要素
                    ExcelHelper.ExportToExcel(JBDataSet, filePath.Replace("争议焦点", "基本要素"));
                    MessageBox.Show("导出表数据成功！");
                }

                //MessageBox.Show("导出数据有误!");
                //return;
            }
            this.Cursor = Cursors.Default;
        }

        private void NewMethod(StringBuilder sb, StringBuilder sb1, string caseCauseColumns, string sysExpressSourceColumns, string regInfoUnitColumns, string regInfoRegexRelationColumns, string regRegexsColumns, DataTable dt, string typeName, DataSet ds)
        {
            sb.Append(string.Format("--{0}类别", typeName) + "\r\n");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string ccid = Convert.ToString(dt.Rows[i]["CC_ID"]);
                //SYS_CaseCause表
                sb.Append("--SYS_CaseCause表 CCID=" + ccid + "\r\n");
                sb.Append("use Ldt_JudgeDocSystem" + "\r\n");
                sb.Append(string.Format(" delete from SYS_CaseCause where CC_ID = '{0}'; ", ccid) + "\r\n");
                sb1.Clear();
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    sb1.Append("N'" + dt.Rows[i][j].ToString() + "',");
                }
                string values = sb1.ToString().Replace("\n", "");
                sb.Append(string.Format(@" insert into SYS_CaseCause ({0}) values({1});", caseCauseColumns.Remove(caseCauseColumns.Length - 1, 1), values.Remove(values.Length - 1, 1)) + "\r\n");
                //维护datatable表
                ds.Tables[0].ImportRow(dt.Rows[i]);
                //SYS_Express_Source表
                DataTable dtExpressSource = SourceBLL.GetExpressSourceData(ccid);
                if (!ds.Tables.Contains("SYS_Express_Source"))
                {
                    DataTable SYS_Express_Source = SourceBLL.GetExpressSourceTableStructs().Clone();
                    SYS_Express_Source.TableName = "SYS_Express_Source";
                    ds.Tables.Add(SYS_Express_Source);
                }
                if (dtExpressSource != null && dtExpressSource.Rows.Count > 0)
                {
                    sb.Append("--SYS_Express_Source表 CCID=" + ccid + "\r\n");
                    sb.Append("use Ldt_JudgeDocSystem" + "\r\n");
                    sb.Append(string.Format(" delete from SYS_Express_Source where CC_ID = '{0}'; ", ccid) + "\r\n");
                    for (int i1 = 0; i1 < dtExpressSource.Rows.Count; i1++)
                    {
                        sb1.Clear();
                        for (int j = 0; j < dtExpressSource.Columns.Count; j++)
                        {
                            sb1.Append("N'" + dtExpressSource.Rows[i1][j].ToString() + "',");
                        }
                        values = sb1.ToString().Replace("\n", "");
                        sb.Append(string.Format(@" insert into SYS_Express_Source ({0}) values({1});", sysExpressSourceColumns.Remove(sysExpressSourceColumns.Length - 1, 1), values.Remove(values.Length - 1, 1)) + "\r\n");
                        ds.Tables[1].ImportRow(dtExpressSource.Rows[i1]);
                    }
                    string regexInfoCodes = SourceBLL.GetRegexInfoCodeByExpressSource(ccid);
                    if (!string.IsNullOrEmpty(regexInfoCodes))
                    {
                        //Reg_InfoUnit表
                        DataTable dtRegInfoUnit = regInfoBll.GetRegexInfoUnit(regexInfoCodes);
                        if (!ds.Tables.Contains("Reg_InfoUnit"))
                        {
                            DataTable Reg_InfoUnit = regInfoBll.GetRegexInfoUnitTableStructs().Clone();
                            Reg_InfoUnit.TableName = "Reg_InfoUnit";
                            ds.Tables.Add(Reg_InfoUnit);
                        }
                        if (dtRegInfoUnit != null && dtRegInfoUnit.Rows.Count > 0)
                        {
                            sb.Append("--Reg_InfoUnit表 EI_ID=" + regexInfoCodes + "\r\n");
                            sb.Append("use LdtCommonManage" + "\r\n");
                            sb.Append(string.Format(" delete from Reg_InfoUnit where EI_ID in({0}); ", regexInfoCodes) + "\r\n");
                            for (int i1 = 0; i1 < dtRegInfoUnit.Rows.Count; i1++)
                            {
                                sb1.Clear();
                                for (int j = 0; j < dtRegInfoUnit.Columns.Count; j++)
                                {
                                    sb1.Append("N'" + dtRegInfoUnit.Rows[i1][j].ToString() + "',");
                                }
                                values = sb1.ToString().Replace("\n", "");
                                sb.Append(string.Format(@" insert into Reg_InfoUnit ({0}) values({1});", regInfoUnitColumns.Remove(regInfoUnitColumns.Length - 1, 1), values.Remove(values.Length - 1, 1)) + "\r\n");
                                ds.Tables[2].ImportRow(dtRegInfoUnit.Rows[i1]);
                            }
                        }

                        DataTable dtRegInfoRegexRelation = regInfoBll.Reg_InfoRegexRelation(regexInfoCodes);
                        if (!ds.Tables.Contains("Reg_InfoRegexRelation"))
                        {
                            DataTable Reg_InfoRegexRelation = regInfoBll.GeReg_InfoRegexRelationTableStructs().Clone();
                            Reg_InfoRegexRelation.TableName = "Reg_InfoRegexRelation";
                            ds.Tables.Add(Reg_InfoRegexRelation);
                        }
                        if (dtRegInfoRegexRelation != null && dtRegInfoRegexRelation.Rows.Count > 0)
                        {
                            sb.Append("--Reg_InfoRegexRelation表 EI_ID=" + regexInfoCodes + "\r\n");
                            sb.Append("use LdtCommonManage" + "\r\n");
                            sb.Append(string.Format(" delete from Reg_InfoRegexRelation where EI_ID in({0}); ", regexInfoCodes) + "\r\n");
                            for (int i1 = 0; i1 < dtRegInfoRegexRelation.Rows.Count; i1++)
                            {
                                sb1.Clear();
                                for (int j = 0; j < dtRegInfoRegexRelation.Columns.Count; j++)
                                {
                                    sb1.Append("N'" + dtRegInfoRegexRelation.Rows[i1][j].ToString() + "',");
                                }
                                values = sb1.ToString().Replace("\n", "");
                                sb.Append(string.Format(@" insert into Reg_InfoRegexRelation ({0}) values({1});", regInfoRegexRelationColumns.Remove(regInfoRegexRelationColumns.Length - 1, 1), values.Remove(values.Length - 1, 1)) + "\r\n");
                                ds.Tables[3].ImportRow(dtRegInfoRegexRelation.Rows[i1]);
                            }
                        }

                        DataTable dtReg_Regexs = regInfoBll.GetReg_Regexs(regexInfoCodes);
                        if (!ds.Tables.Contains("Reg_Regexs"))
                        {
                            DataTable Reg_Regexs = regInfoBll.GeReg_RegexsTableStructs().Clone();
                            Reg_Regexs.TableName = "Reg_Regexs";
                            ds.Tables.Add(Reg_Regexs);
                        }
                        if (dtReg_Regexs != null && dtReg_Regexs.Rows.Count > 0)
                        {
                            sb.Append("--Reg_Regexs表 EI_ID=" + regexInfoCodes + "\r\n");
                            sb.Append("use LdtCommonManage" + "\r\n");
                            sb.Append(string.Format(" delete from Reg_Regexs where ER_ID in(select ER_ID from Reg_InfoRegexRelation where EI_ID in({0})); ", regexInfoCodes) + "\r\n");
                            for (int i1 = 0; i1 < dtReg_Regexs.Rows.Count; i1++)
                            {
                                sb1.Clear();
                                for (int j = 0; j < dtReg_Regexs.Columns.Count; j++)
                                {
                                    sb1.Append("N'" + dtReg_Regexs.Rows[i1][j].ToString() + "',");
                                }
                                values = sb1.ToString().Replace("\n", "");
                                sb.Append(string.Format(@" insert into Reg_Regexs ({0}) values({1});", regRegexsColumns.Remove(regRegexsColumns.Length - 1, 1), values.Remove(values.Length - 1, 1)) + "\r\n");
                                ds.Tables[4].ImportRow(dtReg_Regexs.Rows[i1]);
                            }
                        }
                    }

                }


            }
        }

        #endregion

        #region 导入规则文档事件
        /// <summary>
        /// 导入规则文档事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRuleIn_Click(object sender, EventArgs e)
        {
            try
            {
                bool hasRegex = false;
                StringBuilder sb = new StringBuilder();
                string str = ExcelHelper.GetOpenFilePath();
                if (str == null)
                { return; }
                string fileName = Path.GetFileNameWithoutExtension(str);
                if (clicknode.Tag.ToString() != fileName)
                {
                    MsgBox.Err("导入的Excel文档名称与当前导入节点不匹配");
                    return;
                }
                string ccName, ccNodeTypeName, xPath, purpose, regexCode;
                DataTable dt = new DataTable();
                try
                {
                    dt = ExcelHelper.ImportFromExcel(str, "Sheet1", 1);
                }
                catch (Exception ex)
                {
                    if (ex.Message.Contains("正由另一进程使用") || ex.Message.Contains("The process cannot access the file"))
                    {
                        MsgBox.Err("请将要打开的Excel文档关闭后再试");
                        return;
                    }
                    else
                    {
                        MsgBox.Err("导入Excel文档有错误，请修改后再试！");
                        return;
                    }
                }
                if (dt != null && dt.Rows.Count > 0)
                {
                    DataView dv = dt.DefaultView;
                    DataTable distinctTable = dv.ToTable(true, "节点类型", "节点名称", "Xpath", "用途");
                    for (int i = 0; i < distinctTable.Rows.Count; i++)

                    {
                        ccName = distinctTable.Rows[i]["节点名称"].ToString();
                        ccNodeTypeName = distinctTable.Rows[i]["节点类型"].ToString();
                        xPath = distinctTable.Rows[i]["Xpath"].ToString();
                        purpose = distinctTable.Rows[i]["用途"].ToString();
                        regexCode = casecausebLL.GetRegexInfoCode(ccName, ccNodeTypeName, xPath, purpose, clicknode.Tag.ToString());
                        if (!string.IsNullOrEmpty(regexCode))
                        {
                            hasRegex = true;
                            DataTable dt1 = casecausebLL.GetRegexInfo(regexCode);
                            DataRow[] drs = dt.Select("节点名称='" + ccName + "' and 节点类型= '" + ccNodeTypeName + "' and 用途= '" + purpose + "'");
                            if (dt1 != null && dt1.Rows.Count > 0)
                            {
                                if (drs.Length > 0)
                                {
                                    for (int j = 0; j < drs.Length; j++)
                                    {
                                        Reg_Regexs regexModel = new Reg_Regexs();
                                        if (drs[j]["匹配方式"].ToString() == "匹配")
                                        {
                                            regexModel.ER_ApplyPattern = 0;
                                        }
                                        else if (drs[j]["匹配方式"].ToString() == "排除")
                                        {
                                            regexModel.ER_ApplyPattern = 1;
                                        }
                                        regexModel.ER_Name = regexModel.ER_ApplyPattern == 1 ? "排除" : "匹配";
                                        regexModel.ER_RegexText = drs[j]["正则/关键词"].ToString();

                                        if (dt1.Select("ER_Name='" + regexModel.ER_Name + "' and ER_RegexText= '" + regexModel.ER_RegexText + "'").Length > 0)
                                        //  dt1.Rows[k]["ER_Name"].ToString() == regexModel.ER_Name && dt1.Rows[k]["ER_RegexText"].ToString() == regexModel.ER_RegexText)
                                        {
                                            sb.Append("已经存在该配置,节点名称：" + ccName + " 节点类型：" + ccNodeTypeName + " 用途:" + purpose + " 匹配方式:" + regexModel.ER_Name + " 正则/关键词:" + regexModel.ER_RegexText);
                                            continue;
                                        }
                                        else
                                        {
                                            if (drs[j]["操作类型"].ToString() == "提取")
                                            {
                                                regexModel.ER_OperateType = 1;
                                            }
                                            else if (drs[j]["操作类型"].ToString() == "替换")
                                            {
                                                regexModel.ER_OperateType = 2;
                                            }
                                            else if (drs[j]["操作类型"].ToString() == "匹配")
                                            {
                                                regexModel.ER_OperateType = 3;
                                            }
                                            else if (drs[j]["操作类型"].ToString() == "代码段")
                                            {
                                                regexModel.ER_OperateType = 4;
                                            }
                                            regexModel.ER_RegexText = drs[j]["正则/关键词"].ToString();
                                            regexModel.ER_ReplaceText = drs[j]["替换字符串"].ToString();
                                            regexModel.ER_ID = CreateCode.CreateKeyID("Reg_Regexs");
                                            regexModel.ER_ModifyTime = regexModel.UpdateTime = DateTime.Now;
                                            regexbll.InsertReg_Regexs(regexModel);
                                            Model.Reg_InfoRegexRelation regexInfoModel = new Model.Reg_InfoRegexRelation();
                                            regexInfoModel.ERR_ID = CreateCode.CreateKeyID("Reg_InfoRegexRelation");
                                            regexInfoModel.EI_ID = regexCode;
                                            regexInfoModel.ER_ID = regexModel.ER_ID;
                                            regexInfoModel.ERR_ShowIndex = Convert.ToInt32(drs[j]["显示顺序"]);
                                            regexInfoModel.UpdateTime = DateTime.Now;
                                            regexbll.InsertRegex(regexInfoModel);
                                        }
                                    }
                                }

                            }
                            else
                            {
                                //  DataRow[] drs= dt.Select("节点名称='" + ccName + "' and 节点类型= '" + ccNodeTypeName + "' and 用途= '" + purpose+"'");
                                if (drs.Length > 0)
                                {
                                    for (int j = 0; j < drs.Length; j++)
                                    {
                                        Reg_Regexs regexModel = new Reg_Regexs();
                                        if (drs[j]["匹配方式"].ToString() == "匹配")
                                        {
                                            regexModel.ER_ApplyPattern = 0;
                                        }
                                        else if (drs[j]["匹配方式"].ToString() == "排除")
                                        {
                                            regexModel.ER_ApplyPattern = 1;
                                        }
                                        regexModel.ER_Name = regexModel.ER_ApplyPattern == 1 ? "排除" : "匹配";
                                        if (drs[j]["操作类型"].ToString() == "提取")
                                        {
                                            regexModel.ER_OperateType = 1;
                                        }
                                        else if (drs[j]["操作类型"].ToString() == "替换")
                                        {
                                            regexModel.ER_OperateType = 2;
                                        }
                                        else if (drs[j]["操作类型"].ToString() == "匹配")
                                        {
                                            regexModel.ER_OperateType = 3;
                                        }
                                        else if (drs[j]["操作类型"].ToString() == "代码段")
                                        {
                                            regexModel.ER_OperateType = 4;
                                        }
                                        regexModel.ER_RegexText = drs[j]["正则/关键词"].ToString();
                                        regexModel.ER_ReplaceText = drs[j]["替换字符串"].ToString();
                                        regexModel.ER_ID = CreateCode.CreateKeyID("Reg_Regexs");
                                        regexModel.ER_ModifyTime = regexModel.UpdateTime = DateTime.Now;
                                        regexbll.InsertReg_Regexs(regexModel);
                                        Model.Reg_InfoRegexRelation regexInfoModel = new Model.Reg_InfoRegexRelation();
                                        regexInfoModel.ERR_ID = CreateCode.CreateKeyID("Reg_InfoRegexRelation");
                                        regexInfoModel.EI_ID = regexCode;
                                        regexInfoModel.ER_ID = regexModel.ER_ID;
                                        regexInfoModel.ERR_ShowIndex = Convert.ToInt32(drs[j]["显示顺序"]);
                                        regexInfoModel.UpdateTime = DateTime.Now;
                                        regexbll.InsertRegex(regexInfoModel);
                                    }
                                }
                            }
                        }

                    }
                    if (!hasRegex)
                    {
                        MessageBox.Show("没有需要配置的节点");
                        return;
                    }
                    if (!string.IsNullOrEmpty(sb.ToString()))
                    {
                        MessageBox.Show(sb.ToString());
                        return;
                    }
                    else
                    {
                        MessageBox.Show("导入成功！");
                        return;
                    }
                }
                else
                {
                    MsgBox.Err("导入的Excel内容为空或格式不正确!");
                    return;
                }
            }
            catch (Exception ex)
            {
                MsgBox.Err("导入Excel发生错误!" + ex.Message.ToString());
                return;
            }
        }
        #endregion

        #region 导出规则文档事件
        /// <summary>
        /// 导出规则文档事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRuleOut_Click(object sender, EventArgs e)
        {
            this.contextMenuStrip4.Show(btnRuleOut, 0, this.btnRuleOut.Height);

        }
        #endregion

        #region 获取可以操作民事案由的用户
        public void userYanZhen()
        {
            string path = System.Environment.CurrentDirectory + @"\Users.xml";
            foreach (XmlElement n in getModeListByPath(path, "user/MinShi/add"))
            {
                users.Add(n.Attributes["name"].Value.ToString());
            }
            foreach (XmlElement n in getModeListByPath(path, "user/XinZhen/add"))
            {
                userXZs.Add(n.Attributes["name"].Value.ToString());
            }

        }
        #endregion

        #region 获取XML中某个路径下的节点信息
        /// <summary>
        /// 获取XML中某个路径下的节点信息
        /// </summary>
        /// <param name="path"></param>
        /// <param name="nodePath"></param>
        /// <returns></returns>
        static public XmlNodeList getModeListByPath(string path, string nodePath)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(path);
            XmlNodeList nodeList = doc.SelectNodes(nodePath);
            return nodeList;

        }
        #endregion

        #region 裁判理由和裁判结果类别添加
        public void GetReason()
        {
            dic.Clear();
            dic1.Clear();

            string path = System.Environment.CurrentDirectory + @"\表述工具添加子节点.xml";
            XmlNodeList list = getModeListByPath(path, "添加子节点/裁判理由");
            if (list.Count > 0)
            {



                foreach (XmlElement n in list[0].ChildNodes)
                {
                    table1.Add(n.Name);
                    if (n.HasChildNodes)
                    {
                        List<string> names = new List<string>();
                        foreach (XmlElement m in n.ChildNodes)
                        {

                            names.Add(m.Name);
                        }
                        dic.Add(n.Name, names);
                    }
                    else
                    {
                        dic.Add(n.Name, new List<string>());
                    }

                }
            }
            XmlNodeList list1 = getModeListByPath(path, "添加子节点/裁判结果");
            if (list1.Count > 0)
            {
                List<string> list2 = new List<string>();
                foreach (XmlElement item in list1[0].ChildNodes)
                {
                    list2.Add(item.Name);
                }
                dic1.Add("裁判结果", list2);
            }
        }
        #endregion

        #region 第二类别选择项改变事件
        private void NodeSubTypeList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(NodeSubTypeList.Text))
            {
                if (NodeSubTypeList.Text == "事实要素")
                {
                    radBtnNo.Checked = true;
                    panelBase.Visible = true;
                    panelBase.Location = new System.Drawing.Point(0, 187);
                    panelType.Location = new System.Drawing.Point(0, 220);
                }
                else
                {
                    panelBase.Visible = false;
                    panelType.Location = new System.Drawing.Point(0, 187);
                }
                if (dic.ContainsKey(NodeSubTypeList.Text))
                {
                    if (NodeSubTypeList.Text == "其他")
                    {
                        cmbName.Visible = false;
                        Childname.Visible = true;
                    }
                    else
                    {
                        cmbName.Visible = true;
                        cmbName.DataSource = dic[NodeSubTypeList.Text];
                        Childname.Visible = false;
                    }
                }
            }
        }
        #endregion


        /// <summary>
        /// 添加来源特殊
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button16_Click(object sender, EventArgs e)
        {
            ExpressSourceDefaultSettingsBLL esds = new ExpressSourceDefaultSettingsBLL();
            //获取节点下的类型为争议焦点类型的节点
            DataTable dt = casecausebLL.GetCriminalNodes(clicknode.Tag.ToString());
            StringBuilder sb = new StringBuilder();
            if (dt != null && dt.Rows.Count > 0)
            {
                this.Cursor = Cursors.WaitCursor;
                if (dt.Select(" CC_NodeType=16 ").Length > 0)
                {
                    dt = dt.Select(" CC_NodeType=16 ").CopyToDataTable<DataRow>();
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            DataTable dt1 = SourceBLL.GetSource(dt.Rows[i][0].ToString());
                            if (dt1 != null && dt1.Rows.Count > 0)
                            {
                                DataRow[] dr = dt1.Select(" ES_Purpose_Name='争议焦点匹配' and Source_Name='民事法庭笔录' and Source_ParagraphName='争议焦点原文' and ES_Source_TextType='普通版本' ");
                                if (dr.Length > 0)
                                {
                                    string eiID = dr[0]["EI_ID"].ToString();
                                    Model.Reg_InfoUnit nodeChild = new Model.Reg_InfoUnit();
                                    nodeChild.EI_Name = dt.Rows[i]["CC_Name"].ToString();
                                    nodeChild.EN_ID = "EI_ID1507221438500001";
                                    nodeChild.EI_Remark = "";
                                    nodeChild.EI_ID = newid.CreateID("Reg_InfoUnit");
                                    nodeChild.EI_Code = nodeChild.EI_ID;//编号==ID 
                                    regexbll.AddReg_InfoUnit(nodeChild);

                                    List<Reg_Regexs> regexs = regexbll.GetReg_RegexsByEiid(eiID);
                                    List<Model.Reg_InfoRegexRelation> regRelations = regexbll.GetRegexRelationByEiid(eiID);
                                    if (regexs.Count > 0 && regRelations.Count > 0)
                                    {
                                        for (int j = 0; j < regexs.Count; j++)
                                        {
                                            regexs[j].ER_ID = newid.CreateID("Reg_Regexs");
                                            regexbll.InsertReg_Regexs(regexs[j]);
                                            regRelations[j].EI_ID = nodeChild.EI_ID;
                                            regRelations[j].ER_ID = regexs[j].ER_ID;
                                            regRelations[j].ERR_ID = newid.CreateID("Reg_InfoRegexRelation");
                                            regexbll.InsertRegex(regRelations[j]);
                                        }
                                    }

                                    SysExpressSource model = new SysExpressSource
                                    {
                                        ES_ID = newid.JudgeDoc_CreateID("SYS_Express_Source"),
                                        CC_ID = dt.Rows[i][0].ToString(),
                                        Source_ID = "MSSuitBook",
                                        Source_Name = "起诉状",
                                        Source_ParagraphID = "MS_IM_Litigation Request",
                                        Source_ParagraphName = "诉讼请求",
                                        EsPurposeId = "be907163-377d-4e62-830c-d02de6895d88",
                                        Source_TextType = "1",
                                        EsPurposeName = "争议焦点判断",
                                        CC_RegexInfoCode = nodeChild.EI_Code,
                                    };
                                    if (!SourceBLL.Exists(model.CC_ID, model.Source_ID, model.Source_ParagraphID, model.Source_TextType, model.EsPurposeId))
                                    {
                                        SourceBLL.AddSource(model);
                                    }
                                    else
                                    {
                                        SourceBLL.DelSysExpressSource(model.CC_ID, model.Source_ID, model.Source_ParagraphID, model.Source_TextType, model.EsPurposeId);
                                        SourceBLL.AddSource(model);
                                    }

                                }
                                else
                                {
                                    sb.Append(" " + dt.Rows[i][0].ToString());
                                }
                            }
                        }
                        if (sb.ToString().Trim().Length > 0)
                            MessageBox.Show("以下节点不存在用途为“争议焦点匹配”，来源名称为“民事法庭笔录”，段落名称为“争议焦点原文”，版本为“普通版本”的信息单元" + sb.ToString());
                        this.Cursor = Cursors.Default;
                        MessageBox.Show("添加成功！");
                        ShowSource(clicknode.Tag.ToString());//显示来源
                        return;
                    }
                    else
                    {
                        MessageBox.Show("该节点下没有争议焦点类型的节点");
                        return;
                    }
                }
            }
        }

        #region xmlNode属性
        public class xmlNode
        {
            public string AttributeName { get; set; }

            public string AttributeValue { get; set; }

            public string XmlPath { get; set; }
        }

        /// <summary>
        /// 保存法定刑档次信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSaveDFX_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(cmbDCXZ.Text))
                {
                    MessageBox.Show("请先进行档次选择");
                    cmbDCXZ.Focus();
                    return;
                }
                if (string.IsNullOrEmpty(cmbZXZL.Text))
                {
                    MessageBox.Show("请先进行主刑种类选择");
                    cmbZXZL.Focus();
                    return;
                }
                //修改
                if (punishMent != null && !string.IsNullOrEmpty(punishMent.PGID))
                {
                    XF_Punishment_GradeModel xpg = new XF_Punishment_GradeModel();
                    //修改了档次信息
                    //if (punishMent.PGGrade != cmbDCXZ.Text.ToString().Trim())
                    //{
                    //    //判断修改的档次信息是否已经存在，如果存在直接赋值 否则进行修改
                    //    string primaryKey = xfPunishmentGradeBLL.GetPunishmentGradeID(clicknode.Tag.ToString(), cmbDCXZ.Text.ToString().Trim());
                    //    if (!string.IsNullOrEmpty(primaryKey))
                    //    {
                    //        xpg.PG_ID = primaryKey;
                    //    }
                    //    else
                    //    {
                    xpg.PG_ID = punishMent.PGID;
                    xpg.PG_CaseCauseID = clicknode.Tag.ToString();
                    xpg.PG_Grade = cmbDCXZ.Text.ToString().Trim();
                    xpg.PG_ID = punishMent.PGID;
                    xpg.PG_GradeText = this.txbGradeText.Text.Trim();
                    xpg.PG_ProvInID = Convert.ToInt32(this.txbProvinId.Text.Trim());
                    xfPunishmentGradeBLL.UpdateName(xpg);
                    //    }
                    //}
                    //else
                    //{
                    //    xpg.PG_ID = punishMent.PGID;
                    //}
                    //没有修改档次信息不进行数据的存储
                    if (!string.IsNullOrEmpty(xpg.PG_ID))
                    {
                        if (!string.IsNullOrEmpty(punishMent.GRID))
                        {
                            XF_Grade_RelationtModel xgrm = new XF_Grade_RelationtModel();
                            xgrm.GR_ID = punishMent.GRID;
                            xgrm.PG_ID = xpg.PG_ID;
                            xgrm.GR_TypeID = cmbZXZL.SelectedValue.ToString();
                            xgrm.GR_Minimum = txbZXZdx.Text.Trim();
                            xgrm.GR_Supreme = txbZXZgx.Text.Trim();
                            xgrm.GR_Penalunit = txbZXDW.Text.Trim();
                            xfGradeRelationBLL.UpdateName(xgrm);

                            StringBuilder sbDele = new StringBuilder();
                            if (punishMent.MAID.Count > 0)
                            {
                                foreach (string item in punishMent.MAID)
                                {
                                    sbDele.Append("'" + item + "',");
                                }
                                string mas = sbDele.ToString().Substring(0, sbDele.ToString().Length - 1);
                                xmaBLL.DeleteMaIds(mas);
                            }
                            XF_Major_AddpenaltyModel xfma = new XF_Major_AddpenaltyModel();
                            string primaryKey = string.Empty;
                            if (!string.IsNullOrEmpty(cmbFjxZL1.SelectedValue.ToString()) && !string.IsNullOrEmpty(cmbFjxZL1.Text.Trim()))
                            {
                                primaryKey = Snowflake.GetId().ToString();
                                xfma.MA_ID = primaryKey;
                                xfma.GM_ID = xgrm.GR_ID;
                                xfma.MA_TypeID = cmbFjxZL1.SelectedValue.ToString();
                                xfma.MA_Penalunit = cmbFjxDW1.Text.ToString();
                                xfma.MA_ApplicationID = cmbFjxSY1.SelectedValue.ToString();
                                xfma.MA_Minimum = txbFjxMin1.Text.Trim();
                                xfma.MA_Supreme = txbFjxMax1.Text.Trim();
                                xfma.MA_Optional = cmbSFSelect1.Text.ToString() == "否" ? "0" : "1";
                                xfma.MA_ProvInID = txbFjxPro1.Text.Trim();
                                xmaBLL.Add(xfma);
                            }
                            if (!string.IsNullOrEmpty(cmbFjxZL2.SelectedValue.ToString()) && !string.IsNullOrEmpty(cmbFjxZL2.Text.Trim()))
                            {
                                primaryKey = Snowflake.GetId().ToString();
                                xfma.MA_ID = primaryKey;
                                xfma.GM_ID = xgrm.GR_ID;
                                xfma.MA_TypeID = cmbFjxZL2.SelectedValue.ToString();
                                xfma.MA_Penalunit = cmbFjxDW2.Text.ToString();
                                xfma.MA_ApplicationID = cmbFjxSY2.SelectedValue.ToString();
                                xfma.MA_Minimum = txbFjxMin2.Text.Trim();
                                xfma.MA_Supreme = txbFjxMax2.Text.Trim();
                                xfma.MA_Penalunit = cmbFjxDW2.Text.ToString();
                                xfma.MA_ApplicationID = cmbFjxSY2.SelectedValue.ToString();
                                xfma.MA_Optional = cmbSFSelect2.Text.ToString() == "否" ? "0" : "1";
                                xfma.MA_ProvInID = txbFjxPro2.Text.Trim();
                                xmaBLL.Add(xfma);
                            }
                            if (!string.IsNullOrEmpty(cmbFjxZL3.SelectedValue.ToString()) && !string.IsNullOrEmpty(cmbFjxZL3.Text.Trim()))
                            {
                                primaryKey = Snowflake.GetId().ToString();
                                xfma.MA_ID = primaryKey;
                                xfma.GM_ID = xgrm.GR_ID;
                                xfma.MA_TypeID = cmbFjxZL3.SelectedValue.ToString();
                                xfma.MA_Minimum = txbFjxMin3.Text.Trim();
                                xfma.MA_Supreme = txbFjxMax3.Text.Trim();
                                xfma.MA_Penalunit = cmbFjxDW3.Text.ToString();
                                xfma.MA_ApplicationID = cmbFjxSY3.SelectedValue.ToString();
                                xfma.MA_Optional = cmbSFSelect3.Text.ToString() == "否" ? "0" : "1";
                                xfma.MA_ProvInID = txbFjxPro3.Text.Trim();
                                xmaBLL.Add(xfma);
                            }

                            #region MyRegion
                            //List<string> fjxSet = new List<string>();
                            //if (!string.IsNullOrEmpty(cmbFjxZL1.SelectedValue.ToString()))
                            //{
                            //    fjxSet.Add("0");
                            //}
                            //if (!string.IsNullOrEmpty(cmbFjxZL2.SelectedValue.ToString()))
                            //{
                            //    fjxSet.Add("1");
                            //}
                            //if (!string.IsNullOrEmpty(cmbFjxZL3.SelectedValue.ToString()))
                            //{
                            //    fjxSet.Add("2");
                            //}
                            //if (punishMent.MAID.Count > 0)
                            //{
                            //    for (int i = 0; i < punishMent.MAID.Count; i++)
                            //    {
                            //        if (i == 0 && !string.IsNullOrEmpty(cmbFjxZL1.SelectedValue.ToString()) && !string.IsNullOrEmpty(cmbFjxZL1.Text.Trim()))
                            //        {
                            //            XF_Major_AddpenaltyModel xfma = new XF_Major_AddpenaltyModel();
                            //            xfma.MA_ID = punishMent.MAID[i].Trim();
                            //            xfma.GM_ID = xgrm.GR_ID;
                            //            xfma.MA_TypeID = cmbFjxZL1.SelectedValue.ToString();
                            //            xfma.MA_Minimum = txbFjxMin1.Text.Trim();
                            //            xfma.MA_Supreme = txbFjxMax1.Text.Trim();
                            //            xfma.MA_Penalunit = cmbFjxDW1.Text == null ? "" : cmbFjxDW1.Text.ToString();
                            //            xfma.MA_ApplicationID = cmbFjxSY1.SelectedValue == null ? "" : cmbFjxSY1.SelectedValue.ToString();
                            //            xfma.MA_Optional = cmbSFSelect1.Text.ToString() == "否" ? "0" : "1";
                            //            xfma.MA_ProvInID = txbFjxPro1.Text.Trim();
                            //            xmaBLL.UpdateName(xfma);
                            //            fjxSet.Remove("0");
                            //        }
                            //        else if (i == 1 && !string.IsNullOrEmpty(cmbFjxZL2.SelectedValue.ToString()) && !string.IsNullOrEmpty(cmbFjxZL2.Text.Trim()))
                            //        {
                            //            XF_Major_AddpenaltyModel xfma = new XF_Major_AddpenaltyModel();
                            //            xfma.MA_ID = punishMent.MAID[i].Trim();
                            //            xfma.GM_ID = xgrm.GR_ID;
                            //            xfma.MA_TypeID = cmbFjxZL2.SelectedValue.ToString();
                            //            xfma.MA_Minimum = txbFjxMin2.Text.Trim();
                            //            xfma.MA_Supreme = txbFjxMax2.Text.Trim();
                            //            xfma.MA_Penalunit = cmbFjxDW2.Text == null ? "" : cmbFjxDW2.Text.ToString();
                            //            xfma.MA_ApplicationID = cmbFjxSY2.SelectedValue == null ? "" : cmbFjxSY2.SelectedValue.ToString();
                            //            xfma.MA_Optional = cmbSFSelect2.Text.ToString() == "否" ? "0" : "1";
                            //            xfma.MA_ProvInID = txbFjxPro2.Text.Trim();
                            //            xmaBLL.UpdateName(xfma);
                            //            fjxSet.Remove("1");
                            //        }
                            //        else if (i == 2 && !string.IsNullOrEmpty(cmbFjxZL3.SelectedValue.ToString()) && !string.IsNullOrEmpty(cmbFjxZL3.Text.Trim()))
                            //        {
                            //            XF_Major_AddpenaltyModel xfma = new XF_Major_AddpenaltyModel();
                            //            xfma.MA_ID = punishMent.MAID[i].Trim();
                            //            xfma.GM_ID = xgrm.GR_ID;
                            //            xfma.MA_TypeID = cmbFjxZL3.SelectedValue.ToString();
                            //            xfma.MA_Minimum = txbFjxMin3.Text.Trim();
                            //            xfma.MA_Supreme = txbFjxMax3.Text.Trim();
                            //            xfma.MA_Penalunit = cmbFjxDW3.Text == null ? "" : cmbFjxDW3.Text.ToString();
                            //            xfma.MA_ApplicationID = cmbFjxSY3.SelectedValue == null ? "" : cmbFjxSY3.SelectedValue.ToString();
                            //            xfma.MA_Optional = cmbSFSelect3.Text.ToString() == "否" ? "0" : "1";
                            //            xfma.MA_ProvInID = txbFjxPro3.Text.Trim();
                            //            xmaBLL.UpdateName(xfma);
                            //            fjxSet.Remove("2");
                            //        }
                            //    }
                            //}
                            //if (fjxSet.Count > 0)
                            //{
                            //    serverhelper sqlserverhelper = new serverhelper("");
                            //    string primaryKey = "";
                            //    foreach (var item in fjxSet)
                            //    {
                            //        XF_Major_AddpenaltyModel xfma = new XF_Major_AddpenaltyModel();
                            //        if (item == "0" && !string.IsNullOrEmpty(cmbFjxZL1.SelectedValue.ToString()) && !string.IsNullOrEmpty(cmbFjxZL1.Text.Trim()))
                            //        {
                            //            primaryKey = sqlserverhelper.CreateKeyID();
                            //            xfma.MA_ID = primaryKey;
                            //            xfma.GM_ID = xgrm.GR_ID;
                            //            xfma.MA_TypeID = cmbFjxZL1.SelectedValue.ToString();
                            //            xfma.MA_Minimum = txbFjxMin1.Text.Trim();
                            //            xfma.MA_Supreme = txbFjxMax1.Text.Trim();
                            //            xfma.MA_Penalunit = cmbFjxDW1.Text.ToString();
                            //            xfma.MA_ApplicationID = cmbFjxSY1.SelectedValue.ToString();
                            //            xfma.MA_Optional = cmbSFSelect1.Text.ToString() == "否" ? "0" : "1";
                            //            xfma.MA_ProvInID = txbFjxPro1.Text.Trim();
                            //            xmaBLL.Add(xfma);
                            //        }
                            //        if (!string.IsNullOrEmpty(cmbFjxZL2.SelectedValue.ToString()) && !string.IsNullOrEmpty(cmbFjxZL2.Text.Trim()))
                            //        {
                            //            primaryKey = sqlserverhelper.CreateKeyID();
                            //            xfma.MA_ID = primaryKey;
                            //            xfma.GM_ID = xgrm.GR_ID;
                            //            xfma.MA_TypeID = cmbFjxZL2.SelectedValue.ToString();
                            //            xfma.MA_Minimum = txbFjxMin2.Text.Trim();
                            //            xfma.MA_Supreme = txbFjxMax2.Text.Trim();
                            //            xfma.MA_Penalunit = cmbFjxDW2.Text.ToString();
                            //            xfma.MA_ApplicationID = cmbFjxSY2.SelectedValue.ToString();
                            //            xfma.MA_Optional = cmbSFSelect2.Text.ToString() == "否" ? "0" : "1";
                            //            xfma.MA_ProvInID = txbFjxPro2.Text.Trim();
                            //            xmaBLL.Add(xfma);
                            //        }
                            //        if (!string.IsNullOrEmpty(cmbFjxZL3.SelectedValue.ToString()) && !string.IsNullOrEmpty(cmbFjxZL1.Text.Trim()))
                            //        {
                            //            primaryKey = sqlserverhelper.CreateKeyID();
                            //            xfma.MA_ID = primaryKey;
                            //            xfma.GM_ID = xgrm.GR_ID;
                            //            xfma.MA_TypeID = cmbFjxZL3.SelectedValue.ToString();
                            //            xfma.MA_Minimum = txbFjxMin3.Text.Trim();
                            //            xfma.MA_Supreme = txbFjxMax3.Text.Trim();
                            //            xfma.MA_Penalunit = cmbFjxDW3.Text.ToString();
                            //            xfma.MA_ApplicationID = cmbFjxSY3.SelectedValue.ToString();
                            //            xfma.MA_Optional = cmbSFSelect3.Text.ToString() == "否" ? "0" : "1";
                            //            xfma.MA_ProvInID = txbFjxPro3.Text.Trim();
                            //            xmaBLL.Add(xfma);
                            //        }

                            //    }
                            //} 
                            #endregion
                        }
                    }
                    MessageBox.Show("修改成功！");
                    punishMent = new Punishment();
                    ClearFDX();
                }
                else//添加
                {
                    //保存法定刑幅度档次表
                    XF_Punishment_GradeModel xpg = new XF_Punishment_GradeModel();
                    serverhelper sqlserverhelper = new serverhelper("");
                    string primaryKey = xfPunishmentGradeBLL.GetPunishmentGradeID(clicknode.Tag.ToString(), cmbDCXZ.Text.ToString().Trim());
                    if (!string.IsNullOrEmpty(primaryKey))
                    {
                        xpg.PG_ID = primaryKey;
                    }
                    else
                    {
                        primaryKey = sqlserverhelper.CreateKeyID();
                        xpg.PG_ID = primaryKey;
                        xpg.PG_CaseCauseID = clicknode.Tag.ToString();
                        xpg.PG_Grade = cmbDCXZ.Text.ToString().Trim();
                        xpg.PG_GradeText = this.txbGradeText.Text.Trim();
                        xpg.PG_ProvInID = Convert.ToInt32(this.txbProvinId.Text.Trim());

                        xfPunishmentGradeBLL.Add(xpg);
                    }
                    if (!string.IsNullOrEmpty(xpg.PG_ID))
                    {
                        //保存档次与主刑关系表
                        XF_Grade_RelationtModel xgrm = new XF_Grade_RelationtModel();
                        primaryKey = sqlserverhelper.CreateKeyID();
                        xgrm.GR_ID = primaryKey;
                        xgrm.PG_ID = xpg.PG_ID;
                        xgrm.GR_TypeID = cmbZXZL.SelectedValue.ToString();
                        xgrm.GR_Minimum = txbZXZdx.Text.Trim();
                        xgrm.GR_Supreme = txbZXZgx.Text.Trim();
                        xgrm.GR_Penalunit = txbZXDW.Text.Trim();
                        xfGradeRelationBLL.Add(xgrm);
                        //保存主刑与附加刑关系表
                        XF_Major_AddpenaltyModel xfma = new XF_Major_AddpenaltyModel();
                        if (!string.IsNullOrEmpty(cmbFjxZL1.SelectedValue.ToString()) && !string.IsNullOrEmpty(cmbFjxZL1.Text.Trim()))
                        {
                            primaryKey = sqlserverhelper.CreateKeyID();
                            xfma.MA_ID = primaryKey;
                            xfma.GM_ID = xgrm.GR_ID;
                            xfma.MA_TypeID = cmbFjxZL1.SelectedValue.ToString();
                            xfma.MA_Penalunit = cmbFjxDW1.Text.ToString();
                            xfma.MA_ApplicationID = cmbFjxSY1.SelectedValue.ToString();
                            xfma.MA_Minimum = txbFjxMin1.Text.Trim();
                            xfma.MA_Supreme = txbFjxMax1.Text.Trim();
                            xfma.MA_Optional = cmbSFSelect1.Text.ToString() == "否" ? "0" : "1";
                            xfma.MA_ProvInID = txbFjxPro1.Text.Trim();
                            xmaBLL.Add(xfma);
                        }
                        if (!string.IsNullOrEmpty(cmbFjxZL2.SelectedValue.ToString()) && !string.IsNullOrEmpty(cmbFjxZL2.Text.Trim()))
                        {
                            primaryKey = sqlserverhelper.CreateKeyID();
                            xfma.MA_ID = primaryKey;
                            xfma.GM_ID = xgrm.GR_ID;
                            xfma.MA_TypeID = cmbFjxZL2.SelectedValue.ToString();
                            xfma.MA_Penalunit = cmbFjxDW2.Text.ToString();
                            xfma.MA_ApplicationID = cmbFjxSY2.SelectedValue.ToString();
                            xfma.MA_Minimum = txbFjxMin2.Text.Trim();
                            xfma.MA_Supreme = txbFjxMax2.Text.Trim();
                            xfma.MA_Penalunit = cmbFjxDW2.Text.ToString();
                            xfma.MA_ApplicationID = cmbFjxSY2.SelectedValue.ToString();
                            xfma.MA_Optional = cmbSFSelect2.Text.ToString() == "否" ? "0" : "1";
                            xfma.MA_ProvInID = txbFjxPro2.Text.Trim();
                            xmaBLL.Add(xfma);
                        }
                        if (!string.IsNullOrEmpty(cmbFjxZL3.SelectedValue.ToString()) && !string.IsNullOrEmpty(cmbFjxZL3.Text.Trim()))
                        {
                            primaryKey = sqlserverhelper.CreateKeyID();
                            xfma.MA_ID = primaryKey;
                            xfma.GM_ID = xgrm.GR_ID;
                            xfma.MA_TypeID = cmbFjxZL3.SelectedValue.ToString();
                            xfma.MA_Minimum = txbFjxMin3.Text.Trim();
                            xfma.MA_Supreme = txbFjxMax3.Text.Trim();
                            xfma.MA_Penalunit = cmbFjxDW3.Text.ToString();
                            xfma.MA_ApplicationID = cmbFjxSY3.SelectedValue.ToString();
                            xfma.MA_Optional = cmbSFSelect3.Text.ToString() == "否" ? "0" : "1";
                            xfma.MA_ProvInID = txbFjxPro3.Text.Trim();
                            xmaBLL.Add(xfma);
                        }
                    }
                    MessageBox.Show("添加成功！");
                    ClearFDX();
                }
                LoadPunishmentData();
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存法定刑档次信息发生错误：" + ex.Message);
            }
        }



        private void dgvZX_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {

                //删除
                if (this.dgvZX.Columns[e.ColumnIndex].Name == "Del")
                {
                    DataTable dt = (DataTable)dgvZX.DataSource;
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        string maID = dgvZX.Rows[e.RowIndex].Cells["MA_ID"].Value.ToString();
                        string grID = dgvZX.Rows[e.RowIndex].Cells["GR_ID"].Value.ToString();
                        string pgID = dgvZX.Rows[e.RowIndex].Cells["PG_ID"].Value.ToString();
                        string pgGrade = dgvZX.Rows[e.RowIndex].Cells["PG_Grade"].Value.ToString();
                        if (dt.Select(" PG_Grade='" + pgGrade + "'").Length == 1)
                        {
                            if (xpgrs.GetPunishmentGrade(clicknode.Tag.ToString(), pgGrade))
                            {
                                MessageBox.Show("该法定刑已被（组合）情形所引用，请先删除组合情形引用数据！");
                                return;
                            }
                            else
                            {
                                if (MessageBox.Show("确认要删除该附加刑数据吗？", "此删除不可恢复", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                {
                                    xmaBLL.Delete(maID);
                                    if (dt.Select(" PG_ID='" + pgID + "'").Length == 1)
                                    {
                                        xfGradeRelationBLL.Delete(grID);
                                        xfPunishmentGradeBLL.Delete(pgID);
                                    }
                                    else if (dt.Select(" GR_ID='" + grID + "'").Length == 1)
                                    {
                                        xfGradeRelationBLL.Delete(grID);
                                    }
                                }
                            }
                        }
                        else if (MessageBox.Show("确认要删除该附加刑数据吗？", "此删除不可恢复", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            xmaBLL.Delete(maID);
                            if (dt.Select(" PG_ID='" + pgID + "'").Length == 1)
                            {
                                xfGradeRelationBLL.Delete(grID);
                                xfPunishmentGradeBLL.Delete(pgID);
                            }
                            else if (dt.Select(" GR_ID='" + grID + "'").Length == 1)
                            {
                                xfGradeRelationBLL.Delete(grID);
                            }

                        }
                    }
                    LoadPunishmentData();
                }
                else
                {
                    cmbDCXZ.Text = txbGradeText.Text = txbProvinId.Text = cmbZXZL.Text = txbZXZdx.Text = txbZXZgx.Text = "";
                    cmbFjxZL1.Text = txbFjxMin1.Text = txbFjxMax1.Text = cmbFjxDW1.Text = cmbFjxSY1.Text = cmbSFSelect1.Text = txbFjxPro1.Text = "";
                    cmbFjxZL2.Text = txbFjxMin2.Text = txbFjxMax2.Text = cmbFjxDW2.Text = cmbFjxSY2.Text = cmbSFSelect2.Text = txbFjxPro2.Text = "";
                    cmbFjxZL3.Text = txbFjxMin3.Text = txbFjxMax3.Text = cmbFjxDW3.Text = cmbFjxSY3.Text = cmbSFSelect3.Text = txbFjxPro3.Text = "";
                    DataTable dt = (DataTable)dgvZX.DataSource;
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        punishMent = new Punishment();
                        string pgID = dgvZX.Rows[e.RowIndex].Cells["PG_ID"].Value.ToString();
                        string grID = dgvZX.Rows[e.RowIndex].Cells["GR_ID"].Value.ToString();
                        if (!string.IsNullOrEmpty(pgID) && dt != null && dt.Rows.Count > 0)
                        {
                            if (dt.Select(" PG_ID='" + pgID + "' and GR_ID='" + grID + "' ").Length > 0)
                            {
                                punishMent.PGID = pgID;
                                punishMent.GRID = grID;
                                punishMent.PGGrade = dgvZX.Rows[e.RowIndex].Cells["PG_Grade"].Value.ToString();
                                DataRow[] drs = dt.Select(" PG_ID='" + pgID + "' and GR_ID='" + grID + "' ");
                                DataRow dr = drs[0];
                                cmbDCXZ.Text = dr["PG_Grade"].ToString();
                                txbGradeText.Text = dr["PG_GradeText"].ToString();
                                txbProvinId.Text = dr["PG_ProvInID"].ToString();
                                cmbZXZL.Text = dr["GR_TypeID"].ToString();
                                txbZXZdx.Text = dr["GR_Minimum"].ToString();
                                txbZXZgx.Text = dr["GR_Supreme"].ToString();
                                txbZXDW.Text = dr["GR_Penalunit"].ToString();
                                List<string> lisMaIDs = new List<string>();
                                for (int i = 0; i < drs.Length; i++)
                                {
                                    if (i == 0)
                                    {
                                        lisMaIDs.Add(drs[i]["MA_ID"].ToString());
                                        cmbFjxZL1.Text = drs[i]["MA_TypeID"].ToString();
                                        txbFjxMin1.Text = drs[i]["MA_Minimum"].ToString();
                                        txbFjxMax1.Text = drs[i]["MA_Supreme"].ToString();
                                        cmbFjxDW1.Text = drs[i]["MA_Penalunit"].ToString();
                                        cmbFjxSY1.Text = drs[i]["MA_ApplicationID"].ToString();
                                        cmbSFSelect1.Text = drs[i]["MA_Optional"].ToString();
                                        txbFjxPro1.Text = drs[i]["MA_ProvInID"].ToString();
                                    }
                                    else if (i == 1)
                                    {
                                        lisMaIDs.Add(drs[i]["MA_ID"].ToString());
                                        cmbFjxZL2.Text = drs[i]["MA_TypeID"].ToString();
                                        txbFjxMin2.Text = drs[i]["MA_Minimum"].ToString();
                                        txbFjxMax2.Text = drs[i]["MA_Supreme"].ToString();
                                        cmbFjxDW2.Text = drs[i]["MA_Penalunit"].ToString();
                                        cmbFjxSY2.Text = drs[i]["MA_ApplicationID"].ToString();
                                        cmbSFSelect2.Text = drs[i]["MA_Optional"].ToString();
                                        txbFjxPro2.Text = drs[i]["MA_ProvInID"].ToString();
                                    }
                                    else if (i == 2)
                                    {
                                        lisMaIDs.Add(drs[i]["MA_ID"].ToString());
                                        cmbFjxZL3.Text = drs[i]["MA_TypeID"].ToString();
                                        txbFjxMin3.Text = drs[i]["MA_Minimum"].ToString();
                                        txbFjxMax3.Text = drs[i]["MA_Supreme"].ToString();
                                        cmbFjxDW3.Text = drs[i]["MA_Penalunit"].ToString();
                                        cmbFjxSY3.Text = drs[i]["MA_ApplicationID"].ToString();
                                        cmbSFSelect3.Text = drs[i]["MA_Optional"].ToString();
                                        txbFjxPro3.Text = drs[i]["MA_ProvInID"].ToString();
                                    }
                                }
                                punishMent.MAID = lisMaIDs;
                            }
                        }
                    }
                }
            }

        }

        private void rbtnSingle_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtnSingle.Checked)
            {
                panelZH.Visible = false;
            }
            else
            {
                panelZH.Visible = true;
            }
        }

        private void rbtnZhuHe_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtnZhuHe.Checked)
            {
                panelZH.Visible = true;
            }
            else
            {
                panelZH.Visible = false;
            }
        }

        /// <summary>
        /// 保存情形与法定刑关系信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFDXRelation_Click(object sender, EventArgs e)
        {
            try
            {
                if (rbtnSingle.Checked)
                {
                    if (checkcbSituation1.Text != "请选择")
                    {
                        string pgGrade = cmbDCSelect.Text;
                        if (!string.IsNullOrEmpty(pgGrade))
                        {
                            List<string> ccNodeTypes = checkcbSituation1.checkNodeList;//.CheckBoxItems.Where(x => x.CheckState == CheckState.Checked).Select(x => ((ComboxItem)x.ComboBoxItem).Value).ToList();
                            if (ccNodeTypes.Count > 0)
                            {
                                foreach (string item in ccNodeTypes)
                                {
                                    if (Convert.ToInt32(xrsg.GetQxOldData(item, pgGrade, "1")) <= 0)
                                    {
                                        serverhelper sqlserverhelper = new serverhelper("");
                                        string primaryKey = sqlserverhelper.CreateKeyID();
                                        string prgroupID = sqlserverhelper.CreateKeyID();
                                        XF_Punishiment_RelatStatusModel xprsm = new XF_Punishiment_RelatStatusModel();
                                        xprsm.PR_ID = primaryKey;
                                        xprsm.PR_CaseCauseID = clicknode.Tag.ToString();
                                        xprsm.PR_groupID = prgroupID;
                                        xprsm.PR_SituationTypeID = "1";
                                        bool res = xprs.Add(xprsm);
                                        if (res)
                                        {
                                            XF_PunishimentGrade_RelatStatusModel xprs = new XF_PunishimentGrade_RelatStatusModel();
                                            string pgrId = sqlserverhelper.CreateKeyID();
                                            xprs.PGR_ID = pgrId;
                                            xprs.PR_groupID = prgroupID;
                                            xprs.PG_Grade = pgGrade;
                                            xpgrs.Add(xprs);
                                            string rgID = sqlserverhelper.CreateKeyID();
                                            XF_RelatStatus_GroupModel xrgm = new XF_RelatStatus_GroupModel();
                                            xrgm.RG_ID = rgID;
                                            xrgm.PR_groupID = prgroupID;
                                            xrgm.CC_ID = item;
                                            xrsg.Add(xrgm);
                                        }
                                    }
                                    else
                                    {
                                        MessageBox.Show("已添加过该情形，请重新选择后再试！");
                                        return;
                                    }
                                }

                            }
                        }
                        else
                        {
                            MessageBox.Show("请先选择档次信息后再试！");
                            return;
                        }
                    }
                    else
                    {
                        MessageBox.Show("请先选择情形后再试！");
                        return;
                    }
                }
                else if (rbtnZhuHe.Checked)
                {
                    if (checkcbSituation1.Text != "请选择" && !string.IsNullOrEmpty(checkcbSituation1.Text))
                    {
                        string pgGrade = cmbDCSelect.Text;
                        List<string> ccNodeTypes = checkcbSituation1.checkNodeList;// TreeView.Nodes.Where(x => x.CheckState == CheckState.Checked).Select(x => ((ComboxItem)x.ComboBoxItem).Value).ToList();
                        List<string> ccNodeTypes1 = checkcbSituation2.checkNodeList;// CheckBoxItems.Where(x => x.CheckState == CheckState.Checked).Select(x => ((ComboxItem)x.ComboBoxItem).Value).ToList();
                        List<string> ccNodeTypes2 = checkcbSituation3.checkNodeList;// CheckBoxItems.Where(x => x.CheckState == CheckState.Checked).Select(x => ((ComboxItem)x.ComboBoxItem).Value).ToList();
                        List<string> ccNodeTypes3 = checkcbSituation4.checkNodeList;// CheckBoxItems.Where(x => x.CheckState == CheckState.Checked).Select(x => ((ComboxItem)x.ComboBoxItem).Value).ToList();
                        List<List<string>> lisCount = new List<List<string>>();
                        if (ccNodeTypes.Count > 0)
                        {
                            lisCount.Add(ccNodeTypes);
                        }
                        if (ccNodeTypes1.Count > 0)
                        {
                            lisCount.Add(ccNodeTypes1);
                        }
                        if (ccNodeTypes2.Count > 0)
                        {
                            lisCount.Add(ccNodeTypes2);
                        }
                        if (ccNodeTypes3.Count > 0)
                        {
                            lisCount.Add(ccNodeTypes3);
                        }
                        DataTable dataSource = (DataTable)this.dgvFDXR.DataSource;
                        if (dataSource.Select(string.Format(" PG_Grade='{0}' and  PR_SituationTypeID='{1}' ", pgGrade, 2)).Length != 0)
                        {
                            DataTable table2 = dataSource.Select(string.Format(" PG_Grade='{0}' and  PR_SituationTypeID='{1}' ", pgGrade, 2)).CopyToDataTable<DataRow>();
                            if (!string.IsNullOrEmpty(this.checkcbSituation1.Text))
                            {
                                List<List<string>> lsArray = new List<List<string>>(); char[] separator = new char[] { ',' };
                                List<string> collection = this.checkcbSituation1.Text.Split(separator, StringSplitOptions.RemoveEmptyEntries).ToList<string>();
                                lsArray.Add(collection);
                                if (!string.IsNullOrEmpty(this.checkcbSituation2.Text))
                                {
                                    char[] chArray2 = new char[] { ',' };
                                    List<string> list9 = this.checkcbSituation2.Text.Split(chArray2, StringSplitOptions.RemoveEmptyEntries).ToList<string>();
                                    lsArray.Add(list9);
                                }
                                if (!string.IsNullOrEmpty(this.checkcbSituation3.Text))
                                {
                                    char[] chArray3 = new char[] { ',' };
                                    List<string> list10 = this.checkcbSituation3.Text.Split(chArray3, StringSplitOptions.RemoveEmptyEntries).ToList<string>();
                                    lsArray.Add(list10);
                                }
                                if (!string.IsNullOrEmpty(this.checkcbSituation4.Text))
                                {
                                    char[] chArray4 = new char[] { ',' };
                                    List<string> list11 = this.checkcbSituation4.Text.Split(chArray4, StringSplitOptions.RemoveEmptyEntries).ToList<string>();
                                    lsArray.Add(list11);
                                }
                                //    ress.Clear();
                                //    getQ(lsArray, 0, lsArray.Count);
                                if (lsArray.Count > 0)
                                {
                                    List<string> array = lsArray.Aggregate((m, n) => m.SelectMany(t1 => n.Select(t2 => t1 + ";" + t2).ToList()).ToList()).ToList();
                                    if (array.Count > 0)
                                    {
                                        foreach (DataRow dr in table2.Rows)
                                        {
                                            string name = dr["CCName"].ToString();
                                            if (array.Contains(name))
                                            {
                                                MessageBox.Show("该组合情形已经配置，请重新选择！");
                                                return;
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        if (lisCount.Count > 0)
                        {
                            List<string> array = lisCount.Aggregate((m, n) => m.SelectMany(t1 => n.Select(t2 => t1 + ";" + t2).ToList()).ToList()).ToList();
                            if (array.Count > 0)
                            {
                                foreach (string item in array)
                                {
                                    serverhelper sqlserverhelper = new serverhelper("");
                                    string primaryKey = sqlserverhelper.CreateKeyID();
                                    string prgroupID = sqlserverhelper.CreateKeyID();
                                    XF_Punishiment_RelatStatusModel xprsm = new XF_Punishiment_RelatStatusModel();
                                    xprsm.PR_ID = primaryKey;
                                    xprsm.PR_CaseCauseID = clicknode.Tag.ToString();
                                    xprsm.PR_groupID = prgroupID;
                                    xprsm.PR_SituationTypeID = "2";
                                    bool res = xprs.Add(xprsm);
                                    if (res)
                                    {
                                        XF_PunishimentGrade_RelatStatusModel xprs = new XF_PunishimentGrade_RelatStatusModel();
                                        string pgrId = sqlserverhelper.CreateKeyID();

                                        xprs.PGR_ID = pgrId;
                                        xprs.PR_groupID = prgroupID;
                                        xprs.PG_Grade = pgGrade;
                                        xpgrs.Add(xprs);

                                        string[] str = item.Split(';');
                                        if (str.Length > 0)
                                        {
                                            foreach (var ite in str)
                                            {
                                                XF_RelatStatus_GroupModel xrgm = new XF_RelatStatus_GroupModel();
                                                string rgID = sqlserverhelper.CreateKeyID();
                                                xrgm.RG_ID = rgID;
                                                xrgm.PR_groupID = prgroupID;
                                                xrgm.CC_ID = ite;
                                                xrsg.Add(xrgm);
                                            }
                                        }

                                    }
                                }

                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("请先选择情形后再试！");
                        return;
                    }
                }
                MessageBox.Show("添加成功！");
                LoadFXD();
                LoadQXInfo();
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存出错！" + ex.Message);
            }
        }

        private void dgvFDXR_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.RowIndex >= 0)
                {

                    //删除
                    if (e.ColumnIndex == 3)
                    {
                        DataTable dt = (DataTable)dgvFDXR.DataSource;
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            string PR_ID = dgvFDXR.Rows[e.RowIndex].Cells["PR_ID"].Value.ToString();
                            string PR_groupID = dgvFDXR.Rows[e.RowIndex].Cells["PR_groupID"].Value.ToString();

                            if (MessageBox.Show("确认要删除该条数据吗？", "此删除不可恢复", MessageBoxButtons.YesNo) == DialogResult.Yes)
                            {
                                bool res = xprs.Delete(PR_groupID);
                                bool res1 = xpgrs.Delete(PR_groupID);
                                bool res2 = xrsg.Delete(PR_groupID);
                                MessageBox.Show("删除成功！");
                            }
                        }
                        LoadFXD();
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("删除数据发生错误：" + ex.Message);
            }















            #endregion

            //private void button17_Click(object sender, EventArgs e)
            //{
            //    string str= this.GV_Source.CurrentCell.Value.ToString();
            //    MessageBox.Show(str);
            //}

            //private void tVCaseCause_NodeMouseHover(object sender, TreeNodeMouseHoverEventArgs e)
            //{            
            //    e.Node.ToolTipText=e.Node.Text;         
            //    //var clickPoint = new Point(e.X, e.Y);
            //    //editnode = tVCaseCause.GetNodeAt(clickPoint);
            //    //if (editnode != null)//判断你点的是不是一个节点
            //    //{

            //    //}
            //}
        }

        private void ClearFDX()
        {
            txbZXDW.Text = "月";
            cmbDCXZ.Text = txbGradeText.Text = txbProvinId.Text = cmbZXZL.Text = txbZXZdx.Text = txbZXZgx.Text = "";
            cmbFjxZL1.Text = txbFjxMin1.Text = txbFjxMax1.Text = cmbFjxDW1.Text = cmbFjxSY1.Text = cmbSFSelect1.Text = txbFjxPro1.Text = "";
            cmbFjxZL2.Text = txbFjxMin2.Text = txbFjxMax2.Text = cmbFjxDW2.Text = cmbFjxSY2.Text = cmbSFSelect2.Text = txbFjxPro2.Text = "";
            cmbFjxZL3.Text = txbFjxMin3.Text = txbFjxMax3.Text = cmbFjxDW3.Text = cmbFjxSY3.Text = cmbSFSelect3.Text = txbFjxPro3.Text = "";
        }

        public class Punishment
        {
            /// <summary>
            /// 法定刑幅度档次表主键ID
            /// </summary>
            public string PGID { get; set; }

            /// <summary>
            /// 档次信息
            /// </summary>
            public string PGGrade { get; set; }

            /// <summary>
            /// 档次与主刑关系表主键
            /// </summary>
            public string GRID { get; set; }

            /// <summary>
            /// 主刑与附加刑关系表主键
            /// </summary>
            public List<string> MAID { get; set; }
        }

        /// <summary>
        /// 法定刑清空按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQK_Click(object sender, EventArgs e)
        {
            punishMent = new Punishment();
            ClearFDX();
        }

        /// <summary>
        /// 规则共用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGZShare_Click(object sender, EventArgs e)
        {
            RuleShare rs = new RuleShare(clicknode.Text.ToString(), clicknode.Tag.ToString());
            rs.ShowDialog();
        }

        /// <summary>
        /// 批量独立化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            RuleShare rs = new RuleShare(clicknode.Text.ToString(), clicknode.Tag.ToString(), 1);
            rs.ShowDialog();
        }

        int GridViewRowNumber = 0;
        string slCX = string.Empty;
        private void dataPager1_PageNumberChanging(object sender, Controls.DataPagerPageIndexChangingEventArgs e)
        {
            rbtDispute.Text = "";
            var startRowIndex = e.StartRowIndex;
            var maximumRows = e.MaximumRows;
            var endRowIndex = e.StartRowIndex + e.MaximumRows;
            dispute_infoBLL dll = new dispute_infoBLL();
            DataTable dt = dll.GetDisputeInfoData(clicknode.Tag.ToString(), slCX, startRowIndex, 100);
            if (dt != null && dt.Rows.Count > 0)
            {
                PublicMethod.AddDataTableNum(dt);

                e.TotalCount = dll.GetCount(clicknode.Tag.ToString(), slCX);
                dgvDispute.DataSource = dt;
                rbtDispute.Text = dgvDispute.Rows[0].Cells["DISPUTE_CONTENT"].Value.ToString();

            }
            else
            {
                DataTable dt1 = (DataTable)dgvDispute.DataSource;
                if (dt1 != null)
                {
                    dt1.Rows.Clear();

                }
                dgvDispute.DataSource = dt1;
            }

        }

        private void tabControl3_SelectedIndexChanged(object sender, EventArgs e)
        {
            txbFTContent.Text = txbSLData.Text = "";
            switch (tabControl3.SelectedTab.Name)
            {
                //关联法条
                case "tabPageFT":
                    GetFTData();
                    break;
                //实例数据
                case "tabPageSL":
                    dataPager1.ChangePageNumber(1);
                    break;
            }
        }

        private void GetFTData()
        {
            string webapiUrl1 = ConfigHelper.AppSettings("Getlawprov") + "/lawlibrary/v3/relevantlaws/getlawprov";
            var cause = new { caseCauseID = clicknode.Tag.ToString() };
            lawprovStatisticslawResultModelV3 model = WebUtil.DoPost<lawprovStatisticslawResultModelV3>(webapiUrl1, cause, "UTF-8");
            if (model.result.code == "1")
            {
                DataTable dt = new DataTable();
                dt.Columns.AddRange(new DataColumn[] { new DataColumn("FTNum"), new DataColumn("CatName"), new DataColumn("ProvText") });
                foreach (LawCatModel lc in model.body.dataList)
                {
                    if (lc.lawProvs.Count > 0)
                    {
                        foreach (LatProvModel item in lc.lawProvs)
                        {
                            DataRow dr = dt.NewRow();
                            dr["CatName"] = lc.catName;
                            dr["ProvText"] = item.provName + " " + item.provText.Replace("<br>", System.Environment.NewLine).Trim();
                            dt.Rows.Add(dr);
                        }
                    }
                }

                if (dt.Rows.Count > 0)
                {
                    if (!string.IsNullOrEmpty(txbFTContent.Text.Trim()))
                    {
                        if (dt.Select(" ProvText like '%" + txbFTContent.Text.Trim() + "%' ").Length > 0)
                        {
                            dt = dt.Select(" ProvText like '%" + txbFTContent.Text.Trim() + "%' ").CopyToDataTable();
                        }
                        else
                        {
                            dt.Rows.Clear();
                        }
                    }

                }
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        dt.Rows[i]["FTNum"] = i + 1;
                    }
                }

                dgvFTData.DataSource = dt;
            }
            else
            {
                DataTable dt1 = (DataTable)dgvFTData.DataSource;
                if (dt1 != null)
                {
                    dt1.Rows.Clear();

                }
                dgvFTData.DataSource = dt1;
            }
        }



        /// <summary>
        /// 显示实例数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvDispute_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                rbtDispute.Text = dgvDispute.Rows[e.RowIndex].Cells["DISPUTE_CONTENT"].Value.ToString();
                GridViewRowNumber = e.RowIndex;
            }
        }

        /// <summary>
        /// 实例数据上一条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUp_Click(object sender, EventArgs e)
        {
            if (GridViewRowNumber - 1 >= 0)
            {
                dgvDispute.Focus();
                GridViewRowNumber = GridViewRowNumber - 1;
                dgvDispute.ClearSelection();
                dgvDispute.Rows[GridViewRowNumber].Selected = true;
                rbtDispute.Text = dgvDispute.Rows[GridViewRowNumber].Cells["DISPUTE_CONTENT"].Value.ToString();
            }
        }

        /// <summary>
        /// 实例数据下一条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDown_Click(object sender, EventArgs e)
        {
            if (GridViewRowNumber + 1 <= dgvDispute.Rows.Count - 1)
            {
                dgvDispute.Focus();
                GridViewRowNumber = GridViewRowNumber + 1;
                dgvDispute.ClearSelection();
                dgvDispute.Rows[GridViewRowNumber].Selected = true;
                rbtDispute.Text = dgvDispute.Rows[GridViewRowNumber].Cells["DISPUTE_CONTENT"].Value.ToString();
            }
        }

        /// <summary>
        /// 实例查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnMDCx_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txbSLData.Text.Trim()))
            {
                slCX = "";
            }
            else
            {
                slCX = " and DISPUTE_CONTENT like '%" + txbSLData.Text.Trim() + "%'  ";
            }
            dataPager1.ChangePageNumber(1);
        }

        /// <summary>
        /// 实例排除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnMDPc_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txbSLData.Text.Trim()))
            {
                slCX = "";
            }
            else
            {
                slCX = " and DISPUTE_CONTENT not like '%" + txbSLData.Text.Trim() + "%'  ";
            }
            dataPager1.ChangePageNumber(1);
        }

        /// <summary>
        /// 关联法条查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCx_Click(object sender, EventArgs e)
        {
            GetFTData();
        }

        List<words> wds = new List<words>();
        List<string> lis = new List<string>();
        /// <summary>
        /// 关键词查询同义词
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCXTYC_Click(object sender, EventArgs e)
        {
            if (dgvGJC.SelectedRows.Count > 0)
            {
                this.Cursor = Cursors.WaitCursor;
                StringBuilder sb = new StringBuilder();
                int i = dgvGJC.SelectedRows[0].Index;
                if (dgvGJC.Rows[i].Cells["GJC1"].Value != null && !string.IsNullOrEmpty(dgvGJC.Rows[i].Cells["GJC1"].Value.ToString().Trim()))
                {
                    string gjc1 = dgvGJC.Rows[i].Cells["GJC1"].Value.ToString().Trim();
                    string res = GetGJCData(gjc1, lis, wds);
                    if (!string.IsNullOrEmpty(res))
                    {
                        sb.Append(res);
                    }
                }

                if (dgvGJC.Rows[i].Cells["GJC2"].Value != null && !string.IsNullOrEmpty(dgvGJC.Rows[i].Cells["GJC2"].Value.ToString().Trim()))
                {
                    string gjc2 = dgvGJC.Rows[i].Cells["GJC2"].Value.ToString().Trim();
                    string res = GetGJCData(gjc2, lis, wds);
                    if (!string.IsNullOrEmpty(res))
                    {
                        sb.Append(res);
                    }
                }
                if (dgvGJC.Rows[i].Cells["GJC3"].Value != null && !string.IsNullOrEmpty(dgvGJC.Rows[i].Cells["GJC3"].Value.ToString().Trim()))
                {
                    string gjc3 = dgvGJC.Rows[i].Cells["GJC3"].Value.ToString().Trim();
                    string res = GetGJCData(gjc3, lis, wds);
                    if (!string.IsNullOrEmpty(res))
                    {
                        sb.Append(res);
                    }
                }
                if (sb.Length > 0)
                {
                    dgvGJC.Rows[i].Cells["tyc"].Value = sb.ToString();
                }
                this.Cursor = Cursors.Arrow;
            }
        }

        /// <summary>
        /// 获取同义词接口数据
        /// </summary>
        /// <param name="gjc"></param>
        /// <param name="lis"></param>
        /// <param name="wds"></param>
        /// <returns></returns>
        public string GetGJCData(string gjc, List<string> lis, List<words> wds)
        {
            wds.Clear();
            lis.Clear();
            StringBuilder sb = new StringBuilder();
            if (!string.IsNullOrEmpty(gjc))
            {
                string[] gjc1s = gjc.Split(new char[] { '，' }, StringSplitOptions.RemoveEmptyEntries);
                if (gjc1s.Length > 0)
                {
                    foreach (var item in gjc1s)
                    {
                        if (!lis.Contains(item))
                        {
                            lis.Add(item);
                            wds.Add(new words() { word = item });
                        }
                    }
                }
                if (wds.Count > 0)
                {
                    string webapiUrl1 = ConfigHelper.AppSettings("Gettyc") + "/lexicon/api/v1/words/sameword";
                    WordResultTYC model = WebUtil.DoPost<WordResultTYC>(webapiUrl1, wds);
                    if (model.result.code == "1")
                    {
                        List<thesaurs> thesaurs = model.body;
                        if (thesaurs.Count > 0)
                        {
                            foreach (var item in thesaurs)
                            {
                                if (item.thesaurusWrods.Count > 0)
                                {
                                    foreach (var ite in item.thesaurusWrods)
                                    {
                                        sb.Append(ite.thesaurusWrod.ToString() + ",");
                                    }
                                    sb.Remove(sb.Length - 1, 1);
                                    sb.Append(";");
                                }
                            }

                        }
                    }
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// 关键词保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBCGJC_Click(object sender, EventArgs e)
        {
            if (dgvGJC.Rows.Count > 0)
            {
                CaseCauseWordBLL bll = new CaseCauseWordBLL();
                //删除
                bll.DeleteCaseCauseWord(clicknode.Tag.ToString()); ;

                int i2 = 1;
                List<List<string>> lgjs = new List<List<string>>();
                for (int i = 0; i < dgvGJC.Rows.Count; i++)
                {
                    lgjs.Clear();
                    if (dgvGJC.Rows[i].Cells["GJC1"].Value != null && !string.IsNullOrEmpty(dgvGJC.Rows[i].Cells["GJC1"].Value.ToString().Trim()))
                    {
                        List<string> res = GetListD(dgvGJC.Rows[i].Cells["GJC1"].Value.ToString().Trim());
                        if (res.Count > 0)
                        {
                            lgjs.Add(res);
                        }
                    }
                    if (dgvGJC.Rows[i].Cells["GJC2"].Value != null && !string.IsNullOrEmpty(dgvGJC.Rows[i].Cells["GJC2"].Value.ToString().Trim()))
                    {
                        List<string> res = GetListD(dgvGJC.Rows[i].Cells["GJC2"].Value.ToString().Trim());
                        if (res.Count > 0)
                        {
                            lgjs.Add(res);
                        }
                    }
                    if (dgvGJC.Rows[i].Cells["GJC3"].Value != null && !string.IsNullOrEmpty(dgvGJC.Rows[i].Cells["GJC3"].Value.ToString().Trim()))
                    {
                        List<string> res = GetListD(dgvGJC.Rows[i].Cells["GJC3"].Value.ToString().Trim());
                        if (res.Count > 0)
                        {
                            lgjs.Add(res);
                        }
                    }
                    if (lgjs.Count > 0)
                    {
                        var array = lgjs.Aggregate((m, n) => m.SelectMany(t1 => n.Select(t2 => t1 + "，" + t2).ToList()).ToList()).ToList();
                        if (array.Count > 0)
                        {

                            foreach (string item in array)
                            {
                                string[] strs = item.Split(new char[] { '，' }, StringSplitOptions.RemoveEmptyEntries);
                                if (strs.Length > 0)
                                {
                                    foreach (var ite in strs)
                                    {
                                        CaseCauseWord ccw = new CaseCauseWord();
                                        ccw.CCW_ID = newid.JudgeDoc_CreateID("CaseCauseWord");
                                        ccw.CC_ID = clicknode.Tag.ToString();
                                        ccw.CCW_Type = "1";
                                        ccw.CCW_KeyWord = ite;
                                        ccw.CCW_GroupCode = i2.ToString();
                                        bll.AddCaseCauseWord(ccw);

                                    }
                                }
                                i2++;
                            }
                        }
                    }
                }




                //保存排除词
                if (dgvPCC.Rows.Count > 0)
                {

                    for (int i = 0; i < dgvPCC.Rows.Count; i++)
                    {
                        if (dgvPCC.Rows[i].Cells["GJCPcc"].Value != null && !string.IsNullOrEmpty(dgvPCC.Rows[i].Cells["GJCPcc"].Value.ToString().Trim()))
                        {
                            CaseCauseWord ccw = new CaseCauseWord();
                            ccw.CCW_ID = newid.JudgeDoc_CreateID("CaseCauseWord");
                            ccw.CC_ID = clicknode.Tag.ToString();
                            ccw.CCW_Type = "2";
                            ccw.CCW_KeyWord = dgvPCC.Rows[i].Cells["GJCPcc"].Value.ToString().Trim();
                            bll.AddCaseCauseWord(ccw);
                        }
                    }
                }
                GetGJC();
            }


        }

        public List<string> GetListD(string gjc)
        {
            List<string> lis = new List<string>();
            string[] gjc1s = gjc.Split(new char[] { '，' }, StringSplitOptions.RemoveEmptyEntries);
            if (gjc1s.Length > 0)
            {
                foreach (var item in gjc1s)
                {
                    if (!lis.Contains(item))
                    {
                        lis.Add(item);
                    }
                }
            }
            return lis;
        }

        private void tabControl4_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (tabControl4.SelectedTab.Name)
            {
                //关键词
                case "tabPageGJC":
                    GetGJC();
                    break;
                //化解相关数据
                case "tabPageHJSJ":
                    GetHJSJ();
                    GetXGSJData();
                    break;
            }
        }

        /// <summary>
        /// 获取关键词数据
        /// </summary>
        private void GetGJC()
        {
            CaseCauseWordBLL bll = new CaseCauseWordBLL();
            DataSet ds = bll.GetCaseCauseWordData(clicknode.Tag.ToString());
            if (ds.Tables.Count > 0)
            {
                dgvGJC.DataSource = ds.Tables[0];
                if (ds.Tables.Count > 1)
                {
                    dgvPCC.DataSource = ds.Tables[1];
                }
                else if (dgvPCC.DataSource != null)
                {
                    DataTable dt = (DataTable)dgvPCC.DataSource;
                    dt.Rows.Clear();
                    dgvPCC.DataSource = dt;
                }
            }
            else
            {
                if (dgvGJC.DataSource != null)
                {
                    DataTable dt = (DataTable)dgvGJC.DataSource;
                    dt.Rows.Clear();
                    dgvGJC.DataSource = dt;
                }
                if (dgvPCC.DataSource != null)
                {
                    DataTable dt = (DataTable)dgvPCC.DataSource;
                    dt.Rows.Clear();
                    dgvPCC.DataSource = dt;
                }
            }
        }




        #region 化解相关数据
        /// <summary>
        /// 获取化解相关数据默认配置
        /// </summary>
        public void GetHJSJ()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("hjNRX");
            dt.Columns.Add("hjNR");
            dt.Columns.Add("hjNum");
            string path = @" \\192.168.1.69\智能数据部共享文件\23.矛盾纠纷多元化解平台\2.矛盾纠纷多元化解平台二期方案\2.业务加工\4.加工工具配置\SolveData.xml ";
            if (File.Exists(path))
            {
                foreach (XmlElement item in getModeListByPath(path, "化解相关数据/ContentItem"))
                {
                    //foreach (XmlElement item in n.ChildNodes)
                    //{
                    DataRow dr = dt.NewRow();
                    dr["hjNRX"] = item.Attributes["Name"].Value;
                    dr["hjNum"] = item.Attributes["Code"].Value;
                    dt.Rows.Add(dr);
                    //}
                }
                if (dt.Rows.Count > 0)
                {
                    dgvHJData.DataSource = dt;
                }
                foreach (XmlElement item in getModeListByPath(path, "化解相关数据/Content"))
                {
                    if (item.Attributes["Name"].Value.ToString() == "化解方案")
                    {
                        rtbHJFA.Text = item.Attributes["Formwork"].Value.ToString().Trim();
                    }
                    else if (item.Attributes["Name"].Value.ToString() == "化解建议")
                    {
                        rtbHJJY.Text = item.Attributes["Formwork"].Value.ToString().Trim();
                    }
                    else if (item.Attributes["Name"].Value.ToString() == "化解预期结果")
                    {
                        rtbHJYQJG.Text = item.Attributes["Formwork"].Value.ToString().Trim();
                    }
                }
            }
        }

        /// <summary>
        /// 获取化解相关数据
        /// </summary>
        public void GetXGSJData()
        {
            SYS_CaseCause_SolveBLL csbll = new SYS_CaseCause_SolveBLL();
            DataTable dt = csbll.GetCaseCauseSolve(clicknode.Tag.ToString());
            if (dt != null && dt.Rows.Count > 0)
            {
                DataRow dr = dt.Rows[0];
                rtbHJFA.Text = dr["CCS_SolveProject"].ToString();
                rtbHJJY.Text = dr["CCS_SolveAdvise"].ToString();
                rtbHJYQJG.Text = dr["CCS_SolveExpectResult"].ToString();
                btnSCXGSJ.Enabled = false;
                foreach (DataGridViewRow drr in dgvHJData.Rows)
                {
                    drr.Cells["hjNR"].Value = "";
                }
            }
            else
            {
                btnSCXGSJ.Enabled = true;
            }
        }

        /// <summary>
        /// 生成化解相关数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSCXGSJ_Click(object sender, EventArgs e)
        {
            if (dgvHJData.Rows.Count > 0)
            {
                string hjfa = rtbHJFA.Text.Trim();
                string hjjy = rtbHJJY.Text.Trim();
                string hjyqjg = rtbHJYQJG.Text.Trim();
                foreach (DataGridViewRow dr in dgvHJData.Rows)
                {
                    string code = dr.Cells["hjNum"].Value.ToString();
                    string cotent = dr.Cells["hjNR"].Value.ToString();
                    if (!string.IsNullOrEmpty(cotent.Trim()))
                    {
                        hjfa = hjfa.Replace("{" + code + "}", cotent);
                        hjjy = hjjy.Replace("{" + code + "}", cotent);
                        hjyqjg = hjyqjg.Replace("{" + code + "}", cotent);
                    }
                }
                rtbHJFA.Text = hjfa;
                rtbHJJY.Text = hjjy;
                rtbHJYQJG.Text = hjyqjg;
            }
        }

        /// <summary>
        /// 保存化解相关数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                SYS_CaseCause_SolveBLL bll = new SYS_CaseCause_SolveBLL();
                bll.DeleteCaseCauseData(clicknode.Tag.ToString());
                SYS_CaseCause_Solve sc = new SYS_CaseCause_Solve();
                sc.CCS_ID = newid.JudgeDoc_CreateID("SYS_CaseCause_Solve");
                sc.CC_ID = clicknode.Tag.ToString();
                sc.CCS_SolveProject = rtbHJFA.Text;
                sc.CCS_SolveAdvise = rtbHJJY.Text;
                sc.CCS_SolveExpectResult = rtbHJYQJG.Text;
                bll.AddCaseCauseSolve(sc);
                MessageBox.Show("保存成功！");
                GetXGSJData();
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存失败！" + ex.Message);
            }

        }
        #endregion

        #region 相似违法行为相关操作
        /// <summary>
        /// 批量分词：分词的范围为该节点所有的子级中属于违法行为、违法情形的节点进行分词；
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 批量分词ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string ccid = editnode.Tag.ToString();
                DataTable dt = casecausebLL.GetFCData(ccid);
                if (dt != null && dt.Rows.Count > 0)
                {
                    this.Cursor = Cursors.WaitCursor;
                    foreach (DataRow dr in dt.Rows)
                    {
                        string cid = dr["CC_ID"].ToString();
                        string ccName = dr["CC_Name"].ToString();
                        body1 rc = new body1() { content = ccName.Trim() };
                        string webapiUrl1 = ConfigHelper.AppSettings("Gettyc") + "/lexicon/api/v1/words/cutword";
                        WordResultWord model = WebUtil.DoPost<WordResultWord>(webapiUrl1, rc);
                        if (model.result.code == "1")
                        {
                            List<string> words = model.body;
                            if (words.Count > 0)
                            {
                                StringBuilder sb = new StringBuilder();
                                foreach (var item in words)
                                {
                                    sb.Append(item + "，");
                                }
                                casecausebLL.UpdateKeyWords(cid, sb.ToString().Trim('，'));
                            }
                        }
                    }
                    this.Cursor = Cursors.Arrow;
                    MessageBox.Show("批量分词完毕！");
                    return;
                }
                else
                {
                    MessageBox.Show("没有需要分词的数据！");
                    return;
                }
            }
            catch (Exception ex)
            {
                this.Cursor = Cursors.Arrow;
                MessageBox.Show("批量分词发生错误：" + ex.Message);
                return;
            }
        }

        private void 匹配相似违法行为ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                SYS_CaseCauseSimilarBLL scsbll = new SYS_CaseCauseSimilarBLL();
                string ccid = editnode.Tag.ToString();
                SYS_CaseCause caseCause = casecausebLL.IsParentRealation1(ccid);
                DataTable dt = casecausebLL.GetXZZFData(caseCause.CC_ID);
                if (dt != null && dt.Rows.Count > 0)
                {
                    this.Cursor = Cursors.WaitCursor;
                    foreach (DataRow dr in dt.Rows)
                    {
                        string cid = dr["CC_ID"].ToString();
                        string ccName = dr["CC_Name"].ToString();
                        string keyWords = dr["KeyWords"].ToString();
                        List<string> ppz = keyWords.Split(new char[] { '，' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                        int count = ppz.Count;
                        DataTable dt1 = casecausebLL.GetXZZFKeyWordByID(cid);
                        //思路：循环遍历需要匹配的数据，拿每一个数据与其他数据进行匹配，如果匹配成功，判断是否有历史匹配数据，如果没有直接添加，
                        //如果有则判断历史数据集合中是否已存在，如果存在从集合中去掉，最后判断历史集合中是否还有数据，如果有则判断是否有状态为0的数据，如果有则依次删掉
                        if (ppz.Count > 0 && dt.Select(" CC_ID <> '" + cid + "'").Length > 0)
                        {
                            DataTable dtOther = dt.Select(" CC_ID <> '" + cid + "'").CopyToDataTable();
                            {
                                foreach (DataRow drOther in dtOther.Rows)
                                {
                                    string Othercid = drOther["CC_ID"].ToString();
                                    string OtherccName = drOther["CC_Name"].ToString();
                                    string OtherkeyWords = drOther["KeyWords"].ToString();
                                    List<string> ppzOther = OtherkeyWords.Split(new char[] { '，' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                                    //匹配率=匹配的分词数量/当前节点分词总数>50%
                                    //匹配数量
                                    int countPp = 0;
                                    foreach (var item in ppz)
                                    {
                                        if (ppzOther.Contains(item))
                                        {
                                            countPp++;
                                        }
                                    }
                                    if (countPp > 0 && Convert.ToDouble(countPp) / Convert.ToDouble(count) > 0.5)
                                    {
                                        if (dt1 != null && dt1.Rows.Count > 0)
                                        {
                                            if (dt1.Select(" CCS_SimilarID='" + Othercid + "' ").Length == 1)
                                            {
                                                dt1.Rows.Remove(dt1.Select(" CCS_SimilarID='" + Othercid + "' ")[0]);
                                            }
                                            else
                                            {
                                                SYS_CaseCauseSimilar scs = new SYS_CaseCauseSimilar();
                                                //该节点没有相似数据
                                                serverhelper sqlserverhelper = new serverhelper("");
                                                scs.CCS_ID = sqlserverhelper.CreateKeyID();
                                                scs.CC_ID = cid;
                                                scs.CCS_SimilarID = Othercid;
                                                scs.CCS_State = 0;
                                                scs.UpdateTime = DateTime.Now;
                                                bool res = scsbll.AddCaseCauseSimilar(scs);
                                            }
                                        }
                                        else
                                        {
                                            SYS_CaseCauseSimilar scs = new SYS_CaseCauseSimilar();
                                            //该节点没有相似数据
                                            serverhelper sqlserverhelper = new serverhelper("");
                                            scs.CCS_ID = sqlserverhelper.CreateKeyID();
                                            scs.CC_ID = cid;
                                            scs.CCS_SimilarID = Othercid;
                                            scs.CCS_State = 0;
                                            scs.UpdateTime = DateTime.Now;
                                            bool res = scsbll.AddCaseCauseSimilar(scs);
                                        }
                                    }
                                }
                                if (dt1 != null && dt1.Rows.Count > 0)
                                {
                                    DataRow[] drs = dt1.Select(" CCS_state=0 ");
                                    if (drs.Length > 0)
                                    {
                                        foreach (DataRow drr in drs)
                                        {
                                            string CCS_ID = drr["CCS_ID"].ToString();
                                            bool res1 = scsbll.DelCaseCauseSimilar(CCS_ID);
                                        }
                                    }
                                }
                            }
                        }


                    }
                    this.Cursor = Cursors.Arrow;
                    MessageBox.Show("匹配相似违法行为完毕！");
                    return;
                }
                else
                {
                    MessageBox.Show("没有需要匹配相似违法行为的数据！");
                    return;
                }
            }
            catch (Exception ex)
            {
                this.Cursor = Cursors.Arrow;
                MessageBox.Show("匹配相似违法行为数据发生错误：" + ex.Message);
                return;
            }

        }

        /// <summary>
        /// 相似违法行为全选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvXSWF_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            ///全选与全不选功能
            if (e.RowIndex == -1 && e.ColumnIndex == 0)
            {
                //string revalue = this.dataGridView1.Rows[0].Cells[0].EditedFormattedValue.ToString().ToLower();
                if (num == 0)
                {
                    for (int i = 0; i < dgvXSWF.Rows.Count; i++)
                    {
                        this.dgvXSWF.Rows[i].Cells[0].Value = "true";
                    }
                    num = 1;
                }
                else
                {
                    for (int i = 0; i < dgvXSWF.Rows.Count; i++)
                    {
                        this.dgvXSWF.Rows[i].Cells[0].Value = "false";
                    }
                    num = 0;
                }
                this.dgvXSWF.EndEdit();
            }
        }

        /// <summary>
        /// 显示相似违法行为
        /// </summary>
        private void ShowXSXWData()
        {
            string ccid = clicknode.Tag.ToString();
            SYS_CaseCause caseCause = casecausebLL.GetCaseCauseByCCID(ccid);
            if (!string.IsNullOrEmpty(caseCause.KeyWords))
            {
                txbGJC.Text = lblFC.Text = caseCause.KeyWords;
            }
            else
            {
                txbGJC.Text = lblFC.Text = string.Empty;
            }
            if (!string.IsNullOrEmpty(caseCause.PrimaryKeyWords))
            {
                txbGJC.Text = caseCause.PrimaryKeyWords;
            }
            else
            {
                txbGJC.Text = lblFC.Text;
            }
            DataTable dt = casecausebLL.GetXZZFKeyWordByID(ccid);
            dtXSWFXW.Rows.Clear();
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DataRow dr1 = dtXSWFXW.NewRow();
                    dr1["check"] = false;
                    dr1["xh"] = i + 1;
                    dr1["CC_Name"] = dt.Rows[i]["CC_Name"].ToString();
                    dr1["KeyWords"] = dt.Rows[i]["KeyWords"].ToString();
                    dr1["CCSRightState"] = dt.Rows[i]["CCSRightState"].ToString();
                    dr1["CCSWrongState"] = dt.Rows[i]["CCSWrongState"].ToString();
                    dr1["CCS_ID"] = dt.Rows[i]["CCS_ID"].ToString();
                    dtXSWFXW.Rows.Add(dr1);
                }
                dgvXSWF.DataSource = dtXSWFXW;

            }
            else
            {
                dgvXSWF.DataSource = dtXSWFXW;
            }
        }

        /// <summary>
        /// 显示关联违法行为
        /// </summary>
        private void ShowGLWFData()
        {
            DataTable dtNew = casecausebLL.GetCaseCauseRelationData();
            if (dtNew != null && dtNew.Rows.Count > 0)
            {
                dtNew.Columns.Add("xhGLFW");
                dtNew.Columns.Add("ly");
                dtNew.Columns.Add("cfyj");
                dtNew.Columns.Add("dh");
                dtNew.Columns.Add("bc");
                for (int i = 0; i < dtNew.Rows.Count; i++)
                {
                    dtNew.Rows[i]["xhGLFW"] = i + 1;
                    string AllParentName = dtNew.Rows[i]["AllParentName"].ToString();
                    if (!string.IsNullOrEmpty(AllParentName))
                    {
                        AllParentName = AllParentName.Replace("行政执法,", "");
                        AllParentName = AllParentName.Substring(0, AllParentName.IndexOf(',')).ToString();
                        dtNew.Rows[i]["ly"] = AllParentName;
                    }
                    string ccid = dtNew.Rows[i]["CC_ID"].ToString();
                    if (!string.IsNullOrEmpty(ccid))
                    {
                        string content = string.Empty;
                        DataTable dtt = casecausebLL.GetQuoteLawRelData(ccid);
                        if (dicLaws.ContainsKey(ccid))
                        {
                            content = dicLaws[ccid];
                        }
                        else if (dtt != null && dtt.Rows.Count > 0)
                        {
                            content = GetFTContent(dtt);
                            //根据法条ID获取法规内容
                            if (!dicLaws.ContainsKey(ccid) && !string.IsNullOrEmpty(content))
                            {
                                dicLaws.Add(ccid, content);
                            }
                        }
                        if (!string.IsNullOrEmpty(content))
                        {
                            dtNew.Rows[i]["cfyj"] = content;
                        }

                    }
                    string res = dtNew.Rows[i]["CCR_State"].ToString();
                    switch (res)
                    {
                        case "0":
                            break;
                        case "1":
                            dtNew.Rows[i]["dh"] = true;
                            dtNew.Rows[i]["bc"] = false;
                            break;
                        case "2":
                            dtNew.Rows[i]["dh"] = false;
                            dtNew.Rows[i]["bc"] = true;
                            break;
                    }
                }
                dgvGLFW.DataSource = dtNew;

            }
            else
            {
                DataTable dtt = (DataTable)dgvGLFW.DataSource;
                if (dtt != null)
                { dtt.Rows.Clear(); }
                dgvGLFW.DataSource = dtt;
                return;

            }
        }




        /// <summary>
        /// 根据法条ID获取法规内容
        /// </summary>
        /// <param name="oLR_Law_ProvID"></param>
        /// <returns></returns>
        public string GetFTContent(DataTable ftTable)
        {

            Dictionary<string, string> dicFT = new Dictionary<string, string>();
            string webapiUrl1 = ConfigHelper.AppSettings("Getlawprov") + "/law/lawinfos";
            List<lawModel> lis = new List<lawModel>();
            if (ftTable != null && ftTable.Rows.Count > 0)
            {
                foreach (DataRow dr in ftTable.Rows)
                {
                    string oLR_Law_ProvID = dr["OLR_Law_ProvID"].ToString();
                    lis.Add(new lawModel() { provinids = new List<string>() { oLR_Law_ProvID } });
                }
            }
            lawinfosResponse model = WebUtil.DoPost<lawinfosResponse>(webapiUrl1, lis, "UTF-8");
            if (model.result.code == "1")
            {
                List<responselawcat> rs = model.body;
                if (rs.Count > 0)
                {
                    foreach (responselawcat item in rs)
                    {
                        string catName = item.catname.Trim();
                        List<responselawprov> provs = item.lawprov;
                        StringBuilder sb = new StringBuilder();
                        if (provs.Count > 0)
                        {
                            foreach (responselawprov ite in provs)
                            {
                                string provtext = ite.provtext;
                                if (!string.IsNullOrEmpty(provtext))
                                {
                                    sb.Append(provtext);
                                }
                            }
                        }

                        if (!string.IsNullOrEmpty(sb.ToString()))
                        {
                            if (!dicFT.ContainsKey(catName))
                            {
                                dicFT.Add(catName, sb.ToString());
                            }
                            else
                            {
                                dicFT[catName] = dicFT[catName] + sb.ToString();
                            }
                        }
                    }
                    StringBuilder sb1 = new StringBuilder();
                    if (dicFT.Count > 0)
                    {
                        foreach (string item in dicFT.Keys)
                        {
                            sb1.AppendLine(item);
                            sb1.AppendLine(dicFT[item]);
                        }
                    }
                    return sb1.ToString();
                }
            }
            return "";
        }
        /// <summary>
        /// 相似违法行为勾选对勾和×
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvXSWF_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                #region 对勾和差
                if (e.ColumnIndex == 4 || e.ColumnIndex == 5)
                {
                    DataGridViewCheckBoxCell checkCellRight = (DataGridViewCheckBoxCell)dgvXSWF.Rows[e.RowIndex].Cells["CCSRightState"];
                    DataGridViewCheckBoxCell checkCellwrong = (DataGridViewCheckBoxCell)dgvXSWF.Rows[e.RowIndex].Cells["CCSWrongState"];

                    if (e.ColumnIndex == 4)
                    {
                        if (Convert.ToBoolean(checkCellRight.Value) == true)
                        {
                            checkCellRight.Value = false;
                            checkCellwrong.Value = true;
                        }
                        else
                        {
                            checkCellRight.Value = true;
                            checkCellwrong.Value = false;
                        }

                    }
                    if (e.ColumnIndex == 5)
                    {
                        if (Convert.ToBoolean(checkCellwrong.Value) == true)
                        {
                            checkCellRight.Value = true;
                            checkCellwrong.Value = false;
                        }
                        else
                        {
                            checkCellRight.Value = false;
                            checkCellwrong.Value = true;
                        }
                    }
                    GridViewRowNumber = e.RowIndex;
                    string ccsid = dgvXSWF.Rows[e.RowIndex].Cells["CCS_ID"].Value.ToString();//, Convert.ToInt32(checkCellRight.Value), Convert.ToInt32(checkCellwrong.Value));
                    int state = 0;
                    if (Convert.ToBoolean(checkCellRight.Value))
                    {
                        state = 1;
                    }
                    else if (Convert.ToBoolean(checkCellwrong.Value))
                    {
                        state = 2;
                    }
                    SYS_CaseCauseSimilarBLL scsbll = new SYS_CaseCauseSimilarBLL();
                    bool res = scsbll.UpdateCaseCauseSimilar(ccsid, state.ToString());
                    ShowXSXWData();
                }

                #endregion
            }
        }

        /// <summary>
        /// 批量核查确定与删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDH_Click(object sender, EventArgs e)
        {
            int num = 0;
            for (var i = 0; i <= dgvXSWF.Rows.Count - 1; i++)
            {
                var check = (DataGridViewCheckBoxCell)dgvXSWF.Rows[i].Cells[0];
                if (check.Value != DBNull.Value && Convert.ToBoolean(check.Value))
                {
                    num++;
                }
            }
            if (num == 0)
            {
                MsgBox.Warn("请勾选需要批量修改的数据后再试");
                return;
            }
            if (MessageBox.Show("确认要批量修改吗？", "批量修改", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    SYS_CaseCauseSimilarBLL scsbll = new SYS_CaseCauseSimilarBLL();
                    bool res = false;
                    for (var i = 0; i <= dgvXSWF.Rows.Count - 1; i++)
                    {
                        var check = (DataGridViewCheckBoxCell)dgvXSWF.Rows[i].Cells[0];
                        if (check.Value != DBNull.Value && Convert.ToBoolean(check.Value))
                        {

                            string ccsid = dgvXSWF.Rows[i].Cells["CCS_ID"].Value.ToString();
                            Button btn = (Button)sender;
                            res = scsbll.UpdateCaseCauseSimilar(ccsid, btn.Name == "btnDH" ? "1" : "2");
                        }
                    }
                    if (res)
                    {
                        MsgBox.OK("修改成功!");
                    }
                    else
                    {
                        MsgBox.Warn("修改失败!");
                    }
                }
                catch (Exception error)
                {
                    MsgBox.Warn("删除失败！发生错误！" + error.Message);
                }

                ShowGLWFData();
            }
        }

        #endregion

        /// <summary>
        /// 保存节点关键词
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSaveGJC_Click(object sender, EventArgs e)
        {
            string gjc = txbGJC.Text.Trim();
            if (string.IsNullOrEmpty(gjc))
            {
                MessageBox.Show("请输入需要保存的关键词");
                txbGJC.Focus();
                return;
            }
            else
            {
                string[] str = gjc.Split(new char[] { '，' }, StringSplitOptions.RemoveEmptyEntries);
                StringBuilder sb = new StringBuilder();
                bool res = false;
                foreach (var item in str)
                {
                    if (item.Contains(','))
                    {
                        res = true;
                        MessageBox.Show("关键词中不能包含英文逗号！");
                        txbGJC.Focus();
                        return;
                    }
                    else
                    {
                        sb.Append(item + "，");
                    }
                }
                if (!res)
                {
                    string zzResult = sb.ToString();
                    bool re = casecausebLL.UpCaseCausePrimaryKeyWords(editnode.Tag.ToString(), zzResult.TrimEnd('，'));
                    if (re)
                    {
                        MessageBox.Show("保存成功！");

                    }
                    else
                    {
                        MessageBox.Show("保存失败！");
                        return;
                    }


                }

            }
        }

        Dictionary<string, List<string>> dicpp = new Dictionary<string, List<string>>();
        /// <summary>
        /// 匹配关联违法行为
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 匹配关联违法行为ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            dicpp.Clear();
            //获取需要匹配的数据
            DataTable dt = casecausebLL.GetPPData();
            if (dt != null && dt.Rows.Count > 0)
            {

                //循环遍历数据 每一个进行关键词的匹配 匹配上的分为一组 匹配不上的添加分组
                foreach (DataRow item in dt.Rows)
                {
                    string ccid = item["CC_ID"].ToString();
                    string PrimaryKeyWords = item["PrimaryKeyWords"].ToString();

                    //判断是否存在关键词，不包含并且不匹配则创建，存在则添加ccid
                    if (!dicpp.ContainsKey(PrimaryKeyWords) && !GetPP(PrimaryKeyWords))
                    {
                        List<string> lis = new List<string>();
                        lis.Add(ccid);
                        dicpp.Add(PrimaryKeyWords, lis);
                    }
                    else if (dicpp.ContainsKey(PrimaryKeyWords) && GetPP(PrimaryKeyWords))
                    {
                        List<string> lis = dicpp[PrimaryKeyWords];
                        lis.Add(ccid);
                        dicpp[PrimaryKeyWords] = lis;
                    }
                }
                //形成一个关键词的分组集合，分组的数量大于2才进行入库操作
                if (dicpp.Count > 0)
                {
                    DataTable dtCase = casecausebLL.GetCaseCauseRelation();
                    foreach (string item in dicpp.Keys)
                    {
                        List<string> lis = dicpp[item];
                        //大于2的进行与原来的进行比对，并维护数据库
                        if (lis.Count > 1)
                        {
                            //foreach (var ite1 in lis)
                            //{
                            string res = lis[0];
                            if (dtCase != null && dtCase.Rows.Count > 0 && dtCase.Select(" CC_ID='" + res + "' ").Length > 0)
                            {
                                lis.Remove(res);
                                DataRow dr = dtCase.Select(" CC_ID='" + res + "' ")[0];
                                string CCR_GroupID = dr["CCR_GroupID"].ToString();
                                DataRow[] drs = dtCase.Select(" CCR_GroupID='" + CCR_GroupID + "' and CC_ID<>'" + res + "' ");
                                List<string> liss = new List<string>();
                                foreach (DataRow it in drs)
                                {

                                    if (lis.Contains(it["CC_ID"].ToString()))
                                    {
                                        lis.Remove(it["CC_ID"].ToString());
                                    }
                                    else
                                    {
                                        liss.Add(it["CC_ID"].ToString());
                                    }
                                }
                                //除了第一个节点后还剩下的一条则删掉
                                if (liss.Count == 1)
                                {
                                    bool re = casecausebLL.UpdateSYSCaseCauseRelationByCCID(liss[0], CCR_GroupID);
                                }
                                //剩下的节点处理 先判断存在的进行修改 不存在的进行添加
                                if (lis.Count > 0)
                                {
                                    foreach (string item1 in lis)
                                    {
                                        DataTable dtData = casecausebLL.GetCaseCauseRelationData(item1);
                                        if (dtData != null && dtData.Rows.Count > 0)
                                        {
                                            string CCR_ID = dtData.Rows[0]["CCR_ID"].ToString();
                                            SYS_CaseCauseRelation scr = new SYS_CaseCauseRelation();
                                            scr.CCR_ID = CCR_ID;
                                            scr.CCR_GroupID = CCR_GroupID;
                                            scr.UpdateTime = DateTime.Now;
                                            casecausebLL.UpdateSYSCaseCauseRelation(scr);
                                        }
                                        else
                                        {
                                            SYS_CaseCauseRelation scr = new SYS_CaseCauseRelation();
                                            scr.CCR_ID = newid.JudgeDoc_CreateID("SYS_CaseCauseRelation");
                                            scr.CCR_GroupID = CCR_GroupID;
                                            scr.CC_ID = item1;
                                            scr.UpdateTime = DateTime.Now;
                                            scr.CCR_State = 0;
                                            casecausebLL.InsertSYSCaseCauseRelation(scr);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (lis.Count > 0)
                                {
                                    string CCR_GroupID = Guid.NewGuid().ToString();
                                    foreach (string item1 in lis)
                                    {
                                        SYS_CaseCauseRelation scr = new SYS_CaseCauseRelation();
                                        scr.CCR_GroupID = CCR_GroupID;
                                        DataTable dtData = casecausebLL.GetCaseCauseRelationData(item1);
                                        if (dtData != null && dtData.Rows.Count > 0)
                                        {
                                            string CCR_ID = dtData.Rows[0]["CCR_ID"].ToString();
                                            scr.CCR_ID = CCR_ID;
                                            scr.CCR_GroupID = CCR_GroupID;
                                            scr.UpdateTime = DateTime.Now;
                                            casecausebLL.UpdateSYSCaseCauseRelation(scr);
                                        }
                                        else
                                        {
                                            scr.CCR_ID = newid.JudgeDoc_CreateID("SYS_CaseCauseRelation");
                                            scr.CCR_GroupID = CCR_GroupID;
                                            scr.CC_ID = item1;
                                            scr.UpdateTime = DateTime.Now;
                                            casecausebLL.InsertSYSCaseCauseRelation(scr);
                                        }
                                    }
                                }
                            }
                            //}
                        }
                        else if (lis.Count == 1)//等于1的与历史数据进行比对，并维护数据库
                        {
                            if (dtCase != null && dtCase.Rows.Count > 0 && dtCase.Select(" CC_ID='" + item + "' ").Length > 0)
                            {
                                DataRow dr = dtCase.Select(" CC_ID='" + item + "' ")[0];
                                string CCR_GroupID = dr["CCR_GroupID"].ToString();
                                DataRow[] drs = dtCase.Select(" CCR_GroupID='" + CCR_GroupID + "' ");
                                //当分组的节点有两条时，全部删掉
                                if (drs.Length == 2)
                                {
                                    bool re = casecausebLL.UpdateSYSCaseCauseRelationByGroupID(CCR_GroupID);
                                }
                                else//当分组的节点有多条时，只删掉当前节点的条数
                                {
                                    bool re = casecausebLL.UpdateSYSCaseCauseRelationByCCID(item, CCR_GroupID);
                                }
                            }
                        }
                    }
                }

            }

        }

        /// <summary>
        /// 判断关键词和别的关键词匹配关联违法行为
        /// </summary>
        /// <param name="gjc"></param>
        private bool GetPP(string gjc)
        {
            if (dicpp.Count > 0)
            {
                foreach (string item in dicpp.Keys)
                {
                    string[] li = item.Split(new char[] { '，' }, StringSplitOptions.RemoveEmptyEntries);
                    List<string[]> strs = PermutationAndCombination<string>.GetPermutation(li);
                    if (strs.Count > 0)
                    {
                        foreach (string[] ite in strs)
                        {
                            StringBuilder sb = new StringBuilder();
                            foreach (string it in ite)
                            {
                                sb.Append(it + "，");
                            }
                            if (gjc == sb.ToString().TrimEnd('，'))
                            {
                                return true;
                            }
                        }
                    }
                }
                return false;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 关联违法行为批量修改状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDG_Click(object sender, EventArgs e)
        {
            int num = 0;
            for (var i = 0; i <= dgvGLFW.Rows.Count - 1; i++)
            {
                var check = (DataGridViewCheckBoxCell)dgvGLFW.Rows[i].Cells[0];
                if (check.Value != DBNull.Value && Convert.ToBoolean(check.Value))
                {
                    num++;
                }
            }
            if (num == 0)
            {
                MsgBox.Warn("请勾选需要批量修改的数据后再试");
                return;
            }
            if (MessageBox.Show("确认要批量修改吗？", "批量修改", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    bool res = false;
                    for (var i = 0; i <= dgvGLFW.Rows.Count - 1; i++)
                    {
                        var check = (DataGridViewCheckBoxCell)dgvGLFW.Rows[i].Cells[0];
                        if (check.Value != DBNull.Value && Convert.ToBoolean(check.Value))
                        {
                            string ccrid = dgvGLFW.Rows[i].Cells["CCR_ID"].Value.ToString();
                            Button btn = (Button)sender;
                            res = casecausebLL.UpdateSYSCaseCauseRelationState(ccrid, btn.Name == "btnDG" ? 1 : 2);
                        }
                    }
                    if (res)
                    {
                        MsgBox.OK("修改成功!");
                    }
                    else
                    {
                        MsgBox.Warn("修改失败!");
                    }
                }
                catch (Exception error)
                {
                    MsgBox.Warn("删除失败！发生错误！" + error.Message);
                }

                ShowGLWFData();
            }
        }

        /// <summary>
        /// 保存相似违法行为
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSaveGLFW_Click(object sender, EventArgs e)
        {
            int num = 0;
            for (var i = 0; i <= dgvGLFW.Rows.Count - 1; i++)
            {
                var check = (DataGridViewCheckBoxCell)dgvGLFW.Rows[i].Cells[0];
                if (check.Value != DBNull.Value && Convert.ToBoolean(check.Value))
                {
                    num++;
                }
            }
            if (num == 0)
            {
                MsgBox.Warn("请勾选需要保存的数据后再试");
                return;
            }
            try
            {
                bool res = false;
                for (var i = 0; i <= dgvGLFW.Rows.Count - 1; i++)
                {
                    var check = (DataGridViewCheckBoxCell)dgvGLFW.Rows[i].Cells[0];
                    if (check.Value != DBNull.Value && Convert.ToBoolean(check.Value))
                    {
                        string ccrid = dgvGLFW.Rows[i].Cells["CCR_ID"].Value.ToString();

                        res = casecausebLL.UpdateSYSCaseCauseRelationState(ccrid, Convert.ToBoolean(dgvGLFW.Rows[i].Cells["dh"].Value) ? 1 : 2);
                    }
                }
                if (res)
                {
                    MsgBox.OK("保存成功!");
                }
                else
                {
                    MsgBox.Warn("保存失败!");
                }
            }
            catch (Exception error)
            {
                MsgBox.Warn("保存失败！发生错误！" + error.Message);
            }
            ShowGLWFData();
        }

        /// <summary>
        /// 审核状态事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvGLFW_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && (e.ColumnIndex == 6 || e.ColumnIndex == 7))
            {
                if (e.ColumnIndex == 6)
                {
                    DataGridViewCell cell = dgvGLFW.Rows[e.RowIndex].Cells["dh"];
                    bool ifcheck1 = Convert.ToBoolean(cell.FormattedValue);
                    bool ifcheck2 = Convert.ToBoolean(cell.EditedFormattedValue);
                    if (ifcheck2)
                    {
                        dgvGLFW.Rows[e.RowIndex].Cells["dh"].Value = true;
                        dgvGLFW.Rows[e.RowIndex].Cells["bc"].Value = false;
                    }
                    else
                    {
                        dgvGLFW.Rows[e.RowIndex].Cells["dh"].Value = false;
                        dgvGLFW.Rows[e.RowIndex].Cells["bc"].Value = true;
                    }
                }
                else if (e.ColumnIndex == 7)
                {
                    DataGridViewCell cell = dgvGLFW.Rows[e.RowIndex].Cells["bc"];
                    bool ifcheck2 = Convert.ToBoolean(cell.EditedFormattedValue);
                    if (ifcheck2)
                    {
                        dgvGLFW.Rows[e.RowIndex].Cells["dh"].Value = false;
                        dgvGLFW.Rows[e.RowIndex].Cells["bc"].Value = true;
                    }
                    else
                    {
                        dgvGLFW.Rows[e.RowIndex].Cells["dh"].Value = true;
                        dgvGLFW.Rows[e.RowIndex].Cells["bc"].Value = false;
                    }
                }
            }
        }

        private void dgvGLFW_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            if (this.dgvGLFW.Rows[e.RowIndex].Cells["CCR_State"].Value.ToString() == "0")
            { this.dgvGLFW.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.GreenYellow; }

        }

        #region 行政执法表述工具优化方案0731 20230803功能添加 
        //在添加地域与违法行为时 会先进行删除旧的数据并添加 删除时不会判断该关系是否已经被裁量情节已经配置过 业务进行保证 对裁量情节的添加没有判断是否已经配置过该违法行为的关系
        //操作逻辑为：先进行违法行为与地域的关系配置，然后配置裁量情节与此前配置的地域关系进行再次关联配置 并且配置的父节点为同一个执法领域
        /// <summary>
        /// 地域查询树
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDistrict_Click(object sender, EventArgs e)
        {
            try
            {
                if (cmbCxDistrict.checkNodeList.Count > 0)
                {
                    List<string> allParentIds = new List<string>();
                    tVCaseCause.Nodes[0].Collapse(true);
                    //根据条件查询出匹配地域的节点
                    List<string> ccids = new Xzzf_DisWfRelBLL().GetWfIdsBySystrict(cmbCxDistrict.checkNodeList);
                    allParentIds = casecausebLL.GetAllParentIdByDistrictCondition(ccids);
                    if (allParentIds.Any())
                    {
                        allParentIds.ForEach(x =>
                        {
                            //循环遍历每个节点并定位
                            var NotePidArr = x.Split(',');//所有父级
                            for (var i = 0; i < NotePidArr.Length; i++)
                            {
                                if (i != NotePidArr.Length - 1)
                                {
                                    var Node = FindNode(NotePidArr[i]);
                                    if (Node != null)
                                    {
                                        Node.Expand();//拖出所有父级节点
                                    }
                                }
                                else  //最后一级节点为查找节点
                                {
                                    var node = FindNode(NotePidArr[i]);
                                    node.ForeColor = Color.Red;
                                }
                            }
                        });
                    }
                }
                else
                {
                    MessageBox.Show("请先选择需要查询地域的条件！");
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("根据地域查询节点树出错：" + ex.Message);
            }
        }

        /// <summary>
        /// 地域改变事件 地域改变后加载下方违法行为
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbDistrict_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (xzzfDisWfRelCxModels.Any() && !string.IsNullOrWhiteSpace(cmbDistrict.SelectedValue.ToString()))
                {
                    showDisWfRelCxModels = xzzfDisWfRelCxModels.Where(x => x.CC_District == cmbDistrict.SelectedValue.ToString()).ToList();
                }
                else
                {
                    showDisWfRelCxModels.Clear();
                }
                dgvAddWfClRel.DataSource = showDisWfRelCxModels;

            }
            catch (Exception ex)
            {
                MessageBox.Show("地域改变后加载下方违法行为出错：" + ex.Message);
            }
        }

        /// <summary>
        /// 保存地域违法行为与裁量情节关系配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnWfclRelSave_Click(object sender, EventArgs e)
        {
            try
            {
                List<Xzzf_WfClRel> wfClRels = new List<Xzzf_WfClRel>();
                for (var i = 0; i <= dgvAddWfClRel.Rows.Count - 1; i++)
                {
                    var check = (DataGridViewCheckBoxCell)dgvAddWfClRel.Rows[i].Cells["xzWfClRel"];
                    if (check.Value != DBNull.Value && Convert.ToBoolean(check.Value))
                    {
                        string rcId = dgvAddWfClRel.Rows[i].Cells["RC_ID"].Value.ToString();
                        wfClRels.Add(new Xzzf_WfClRel() { ZJ_ID = newid.JudgeDoc_CreateID("Xzzf_WfClRel"), CL_ID = clicknode.Tag.ToString(), RC_ID = rcId });
                    }
                }
                if (wfClRels.Any())
                {
                    Xzzf_WfClRelBLL wfClRelBll = new Xzzf_WfClRelBLL();
                    bool res = wfClRelBll.InsertWfClRel(wfClRels);
                    if (res)
                    {
                        MessageBox.Show("添加成功！");
                        GetdgvWfClRelData();
                    }
                    else
                    {
                        MessageBox.Show("添加失败！");
                    }
                }
                else
                {
                    MessageBox.Show("请选择需要保存的数据后再试！");
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存地域违法行为与裁量情节关系配置出错：" + ex.Message);
            }
        }

        /// <summary>
        /// 获取地域违法行为与裁量情节关系配置数据
        /// </summary>
        private void GetdgvWfClRelData()
        {
            try
            {
                List<Xzzf_WfClRelCXModel> wfClRelModels = new Xzzf_WfClRelBLL().GetDisWfRelData(clicknode.Tag.ToString());
                if (wfClRelModels.Any())
                    dgvWfClRelData.DataSource = wfClRelModels;
            }
            catch (Exception ex)
            {
                MessageBox.Show("获取地域违法行为与裁量情节关系配置数据出错：" + ex.Message);
            }
        }

        /// <summary>
        /// 删除地域违法行为与裁量情节关系配置数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnWfclRelUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                bool delState = false;
                for (var i = 0; i <= dgvWfClRelData.Rows.Count - 1; i++)
                {
                    var check = (DataGridViewCheckBoxCell)dgvWfClRelData.Rows[i].Cells["wfClRelCheck"];
                    if (check.Value != DBNull.Value && Convert.ToBoolean(check.Value))
                    {
                        string zjId = dgvWfClRelData.Rows[i].Cells["ZJ_ID"].Value.ToString();
                        delState = new Xzzf_WfClRelBLL().DelWfClRelByZjId(zjId);
                    }
                }
                if (delState)
                {
                    MessageBox.Show("删除成功！");
                    GetdgvWfClRelData();
                }
                else
                {
                    MessageBox.Show("删除失败！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("删除地域违法行为与裁量情节关系配置数据出错：" + ex.Message);
            }
        }

        /// <summary>
        /// 添加地域违法行为与裁量关系配置全选不全选功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvAddWfClRel_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                ///全选与全不选功能
                if (e.RowIndex == -1 && e.ColumnIndex == 0)
                {
                    string revalue = this.dgvAddWfClRel.Rows[0].Cells[0].EditedFormattedValue.ToString().ToLower();
                    if (revalue == "false")
                    {
                        for (int i = 0; i < dgvAddWfClRel.Rows.Count; i++)
                        {
                            this.dgvAddWfClRel.Rows[i].Cells[0].Value = "true";
                        }
                    }
                    else
                    {
                        for (int i = 0; i < dgvAddWfClRel.Rows.Count; i++)
                        {
                            this.dgvAddWfClRel.Rows[i].Cells[0].Value = "false";
                        }
                    }
                    this.dgvAddWfClRel.EndEdit();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("添加地域违法行为与裁量关系配置全选不全选功能出错：" + ex.Message);
            }
        }

        /// <summary>
        /// 添加地域违法行为与裁量关系配置全选不全选功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvWfClRelData_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                ///全选与全不选功能
                if (e.RowIndex == -1 && e.ColumnIndex == 0)
                {
                    string revalue = this.dgvWfClRelData.Rows[0].Cells[0].EditedFormattedValue.ToString().ToLower();
                    if (revalue == "false")
                    {
                        for (int i = 0; i < dgvWfClRelData.Rows.Count; i++)
                        {
                            this.dgvWfClRelData.Rows[i].Cells[0].Value = "true";
                        }
                    }
                    else
                    {
                        for (int i = 0; i < dgvWfClRelData.Rows.Count; i++)
                        {
                            this.dgvWfClRelData.Rows[i].Cells[0].Value = "false";
                        }
                    }
                    this.dgvWfClRelData.EndEdit();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("添加地域违法行为与裁量关系配置全选不全选功能出错：" + ex.Message);
            }
        }

        /// <summary>
        /// 违法行为模糊查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearch_Click(object sender, EventArgs e)
        {
            //通过关键词能搜索到数据则显示匹配数据，搜索不到则不显示，清空查询则显示全部
            if (!string.IsNullOrWhiteSpace(txbSearch.Text.Trim()))
            {
                if (showDisWfRelCxModels.Any())
                {
                    if (showDisWfRelCxModels.Where(x => x.CC_Name.Contains(txbSearch.Text.Trim())).Any())
                    {
                        dgvAddWfClRel.DataSource = showDisWfRelCxModels.Where(x => x.CC_Name.Contains(txbSearch.Text.Trim())).ToList();
                    }
                    else
                    {
                        dgvAddWfClRel.DataSource = new List<Xzzf_DisWfRelCXModel>();
                    }
                }
            }
            else
            {
                if (showDisWfRelCxModels.Any())
                {
                    dgvAddWfClRel.DataSource = showDisWfRelCxModels;
                }
            }
            #endregion
        }

        public class words
        {
            public string word { get; set; }
        }

        /// <summary>
        /// LawInfos接口的Model
        /// </summary>
        public class lawModel
        {
            /// <summary>
            /// 法规ID
            /// </summary>
            public string catinid { get; set; }
            /// <summary>
            /// 条文列表
            /// </summary>
            public List<string> provinids { get; set; }
        }
    }
}